(define (interchange list)
(if (empty? list)
list
(interchange (append (car (cdr list) X)))))我需要创建一个函数来交换方案列表中的元素对。这就是我到目前为止想出的方法,但我在empty?中遇到错误
Error
empty?: undefined;
cannot reference undefined identifier
function call output
(interchange '( )) ()
(interchange '(a)) (a)
(interchange '(a b)) (b a)
(interchange '(a b c)) (b a c)
(interchange '(a 1 b 2 c 3 d 4)) (1 a 2 b 3 c 4 d)
(interchange '(hello you -12.34 5 -6 enough)) (you hello 5 -12.34 enough -6)发布于 2015-05-13 07:31:17
试试这个:
(define (interchange lst)
(if (or (null? lst) (null? (cdr lst))) ; if the list has 0 or 1 elements left
lst ; then return the list, we're done
(cons (cadr lst) ; otherwise grab the second element
(cons (car lst) ; and the first element
(interchange (cddr lst)))))) ; and move forward two elements诀窍是在每次迭代中处理两个元素,小心处理边缘情况。对于示例输入,它的工作方式与预期相同:
(interchange '())
=> '()
(interchange '(a))
=> '(a)
(interchange '(a b))
=> '(b a)
(interchange '(a b c))
=> '(b a c)
(interchange '(a 1 b 2 c 3 d 4))
=> '(1 a 2 b 3 c 4 d)
(interchange '(hello you -12.34 5 -6 enough))
=> '(you hello 5 -12.34 enough -6)发布于 2015-05-14 04:42:12
#lang racket
(define (interchange xs)
(match xs
[(or '() (list _)) ; if the list is empty or has one element
xs] ; then interchange keeps the original list
[(list* x y more) ; if the list has two or more elements,
(list* y x (interchange more))])) ; then the result consists of the two
; ; first elements (with the order swapped)
; ; followed by the result of
; ; interchanging the remaining elements.
(interchange '( ))
(interchange '(a))
(interchange '(a b))
(interchange '(a b c))
(interchange '(a 1 b 2 c 3 d 4))
(interchange '(hello you -12.34 5 -6 enough)) 输出:
'()
'(a)
'(b a)
'(b a c)
'(1 a 2 b 3 c 4 d)
'(you hello 5 -12.34 enough -6)https://stackoverflow.com/questions/30202853
复制相似问题