lisp自行开发的递归反向函数

时间:2017-03-22 04:49:20

标签: function lisp reverse

我在lisp中编写了一个列表反向函数,我想测试它,但是我有一个错误,我无法解决它 功能和调用如下:

    (defun myreverse (list)
    (cond((null list) nil))
    (cons (myreverse(cdr list) (car list))))


    (myreverse '(1 2 3))

任何帮助将不胜感激......

2 个答案:

答案 0 :(得分:0)

当您defun myreverse(list)时的论据,因此当您致电(myreverse '(1 2 3)) list时,(1 2 3)会被绑定。(myreverse '(2 3) 1)

由于列表不为null,您突然list(2 3)绑定到1,但(defun test (a &optional (b 0) (c 0)) (+ a b c)) (test 10) ; ==> 10 (test 10 1 2) ; ==> 13 绑定到什么?您只有一个参数,因此调用无效并保证错误。

提示1:有一种方法可以生成可选参数:

Mocha package

提示2:您需要构建一个列表,而不仅仅是传递一个裸元素。传递的列表将是下一轮的尾部,直到添加每个元素。

答案 1 :(得分:0)

错误答案(或其中一个错误答案):

(defun reverse (list)
    (cond ((null list) list)
          (t (append (reverse (cdr list)) (cons (car list) nil)))))

更好的答案:

(defun reverse (list)
     (reverse-aux list nil))
(defun reverse-aux (list result)
     (cond ((null list) result)
           (t (reverse-aux (cdr list) (cons (car list) result)))))

这是我们使用的基本示例,与'追加'的定义相比较在课程中区分尾递归。