我试着像这样做这个练习:
(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 ...
我是一名优秀的程序员,十分优秀!