Can anyone give me some hints about this question(Family tree)?
It comes from my homework assignments. There is a family tree
a + b
/ | | \
c+u d+c e+w f
/ | \ / \
m+x n+y o p q
|
r
a and b is the oldest. and every married people the second person is not part of the original family. Now I need to write the spouse, sibling, children ,grandchildren, parents and grandparents function.
I wrote the list as below: ( (father mother) chlid1 child2 child3)
(((a b) c d e f) ((c u) m n o) ((d v) nil) ((e w) p q) (f nil) ((m x) r) ((n y) nil) (o nil) (p nil) (q nil) )
I have some problems with sibling function, here is my code.
(defun sibling (arglst lst)
(cond
((eql
arglst (cdr (car lst)))
(rest (cdr lst))
)
(T (sibling (rest l开发者_开发百科st) arglst))
)
I knew it was wrong, but I don't how to revise it.. and I also need some help with other functions. hope can get some hints from u guys.
Since this is homework, I won't give the full solution, but this should suffice for you to solve the rest:
(defparameter *family* '(((a b) c d e f)
((c u) m n o)
((d v) nil)
((e w) p q)
(f nil)
((m x) r)
((n y) nil)
(o nil)
(p nil)
(q nil)))
(defun siblings (person family)
"Return a list of PERSON's siblings."
(remove person (cdr (find person family :key #'cdr :test #'member))))
(defun siblingsp (person1 person2 family)
"Are PERSON1 and PERSON2 siblings?"
(find person2 (siblings person1 family)))
(defun parents (person family)
"Return a list of PERSON's parents."
(car (find person family :key #'cdr :test #'member)))
(defun parentp (parent child family)
"Is PARENT a parent of CHILD?"
(find parent (parents child family)))
Try it:
CL-USER> (siblings 'p *family*)
(Q)
CL-USER> (siblingsp 'q 'p *family*)
P
CL-USER> (parents 'p *family*)
(E W)
Now, to find the grandparents for example, you just have to understand what grandparents are: (A list of) The parents of both parents. Then, ask yourself how it is for grandchildren. Finally, the spouse
function should be rather easy, given this example.
I don't know why it can only return first level and second level,for example. a returns b, c returns u . but when I entere m ,it returns an erro :
- MEMBER: A proper list must not end with F
.
I checked the code and didn't find any problems. why it cannot search the third level? but it can find grandchildren,so I think if it can do grandchildren search why it cannot do spouse search? is there something wrong with Member
function? anyway, your code is really simple and easy to read and understand. Thanks a lot.
(defun spouse ( family-tree2 person) ;Find person's spouse
(remove person (car (find person family-tree2 :key #'car :test #'member)))
);end
精彩评论