gpt4 book ai didi

LISP 练习秘诀

转载 作者:太空宇宙 更新时间:2023-11-03 19:02:46 27 4
gpt4 key购买 nike

Family Tree Exercise

我试着像这样做这个练习:

(defconstant *family-tree* 
'((father Barack Pat) (mother Michelle Pat)
(father GeorgeW Peter) (mother Laura Peter)
(father GeogerH James (mother Barbara James)
(father Bill Jane) (mother Hillary Jane)
(father James Mark) (mother Jane Mark)
(father Peter Mary) (mother Pat Mary)
(father Mark John) (mother Mary John))))

但我不确定这是否是最好的方法。此外,我不知道如何创建“ parent ”和“祖 parent ”功能。我真的很感激任何帮助。谢谢

最佳答案

您可能想从小步骤开始:

(defun make-person (name &optional father mother)
(cons name (cons father mother)))

现在您可以创建您的家谱:

(defconstant *family-tree* 
(make-person 'john
(make-person 'mark
(make-person 'james
...)
(make-person 'jane
...))
(make-person 'mary
(make-person ...)
(make-person ...))))

在树中找人需要递归:

(defun find-person (tree name)
(if (eq (car tree) name)
tree
(or (find-person (cadr tree) name)
(find-person (cddr tree) name))))

您实际上可以将 cadr 替换为 father-tree 并将 cddr 替换为 mother-tree。(你也可以定义tree-name来调用car)。

现在找 parent 和祖 parent 应该很容易了:

(defun parents (tree name)
(let ((person (find-person tree name)))
(list (caadr person) ; or (tree-name (tree-father person))
(caddr person)))) ; or ...

关于LISP 练习秘诀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25771708/

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