我必须编写一个执行以下操作的scheme函数:
定义一个名为(rev p)的SCHEME函数,该函数将一对作为参数并计算为另一对具有相反的对p中的第一和第二元素。例如,
(rev(缺点1 2))(2。1)
这是我的代码:
(define (rev p)
(cond ((null? p) '())
(not (pair? (car p)) p)
(else (append (rev (cdr p)) (list (rev (car p))))
但是,当我测试它应该返回(2。1)时,我的代码返回(1。2)。
pair,这很简单,您甚至不需要进行递归!并记住使用cons
,而不是append
:
(define (rev p)
(cond ((not (pair? p)) p)
(else (cons (cdr p) (car p)))))
例如:
(rev '()) => '() (rev 5) => 5 (rev (cons 1 2)) => '(2 . 1)
(define (rev p)
(if (pair? p)
(cons (cdr p) (car p))
p))
(define rev
(lambda (l acc)
(if (null? l)
acc
(rev (cdr l)(cons (car l) acc)))))
(rev '(1 2 3) '())