gpt4 book ai didi

lisp - 需要了解带递归的 LISP 程序

转载 作者:太空宇宙 更新时间:2023-11-03 18:50:35 25 4
gpt4 key购买 nike

(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)我试图了解它是如何工作的。有人可以说明发生了什么事吗?我试着按照代码写在纸上,但我失败了。

最佳答案

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)

除此之外,我不确定如何提供更多帮助。

关于lisp - 需要了解带递归的 LISP 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16492069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com