需要了解带递归的LISP程序

时间:2013-05-10 23:12:59

标签: lisp clisp

(defun help(a x)
  (if (null x) nil
    (cons (cons a (car x)) (help a (cdr x)))))

(defun partition(x)
    (if (null x) '(nil)
    (append (help (car x) (partition(cdr x))) (partition(cdr x)))))

这样的工作原理如下:(partition '(a b)) -> ((A B) (A) (B) NIL) 我试图了解它是如何工作的。有人可以说明结果是什么吗?我试着遵循这些代码并写在纸上,但我失败了。

1 个答案:

答案 0 :(得分:6)

trace函数允许您在LISP REPL中可视化函数调用。

sbcl

的输出示例
* (defun help(a x)
  (if (null x) nil
    (cons (cons a (car x)) (help a (cdr x)))))

HELP
* (defun partition(x)
  (if (null x) '(nil)
    (append (help (car x) (partition(cdr x))) (partition(cdr x)))))

PARTITION
* (trace help)

(HELP)
* (trace partition)

(PARTITION)
* (partition '(a b))
  0: (PARTITION (A B))
    1: (PARTITION (B))
      2: (PARTITION NIL)
      2: PARTITION returned (NIL)
      2: (HELP B (NIL))
        3: (HELP B NIL)
        3: HELP returned NIL
      2: HELP returned ((B))
      2: (PARTITION NIL)
      2: PARTITION returned (NIL)
    1: PARTITION returned ((B) NIL)
    1: (HELP A ((B) NIL))
      2: (HELP A (NIL))
        3: (HELP A NIL)
        3: HELP returned NIL
      2: HELP returned ((A))
    1: HELP returned ((A B) (A))
    1: (PARTITION (B))
      2: (PARTITION NIL)
      2: PARTITION returned (NIL)
      2: (HELP B (NIL))
        3: (HELP B NIL)
        3: HELP returned NIL
      2: HELP returned ((B))
      2: (PARTITION NIL)
      2: PARTITION returned (NIL)
    1: PARTITION returned ((B) NIL)
  0: PARTITION returned ((A B) (A) (B) NIL)
((A B) (A) (B) NIL)

除此之外,我并不完全确定如何获得更多帮助。