如何在方案中编写反函数?

问题描述 投票:0回答:3

我必须编写一个执行以下操作的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)。

scheme racket computer-science
3个回答
0
投票
如果只是要反转的

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)


0
投票
或等同于:

(define (rev p) (if (pair? p) (cons (cdr p) (car p)) p))


0
投票
(define rev (lambda (l acc) (if (null? l) acc (rev (cdr l)(cons (car l) acc))))) (rev '(1 2 3) '())
© www.soinside.com 2019 - 2024. All rights reserved.