2015-05-22 153 views
1

我是lisp的初学者。 ((name1,second)(name2,second2))从lisp列表中获取元素

我的函数的目标是获取列表的第二个元素名称作为它的第一个节点。

例如: 我的列表是:((name1,second1)(name2,second2)) getelement list name1应该返回second1。

(defun getelement (list name) 
    (if (eq list '()) 
    (if (string= (caar list) name) 
     (car (car (cdr list))) 
     (getelement (cdr list) name) 
    ) 
    () 
) 
) 

但我得到这个错误。我真的不明白我的代码发生了什么。我想表达之前把'......

Error: The variable LIST is unbound. 
Fast links are on: do (si::use-fast-links nil) for debugging 
Error signalled by IF. 
Backtrace: IF 
+0

什么是节点列表? – Bill

+0

@Bill对不起,我更改了变量的名称,但忘记了这个。 nodelist是list(参数)。 – anothertest

+0

当您使用正确的变量名称时它是否提供错误消息?如果是这样的话:使用什么lisp,以及如何调用你的函数? –

回答

1
(defun get-element (list name) 
    (cadr (assoc name list :test #'string=))) 
3
  1. 的,如果条款是错误的顺序。
  2. 当字符串匹配,你正在服用的下一个元素(CDR),而不是匹配到的元素(车)

这应该工作:

(defun getelement (list name) 
    (if (eq list '()) ;end of list,... 
     '() ;return empty list 
     (if (string= (caar list) name) ;matches, 
      (car (car list)) ;take the matching element 
      (getelement (cdr list) name)))) 
+0

该函数应该返回匹配的元素_following_,即(car(cdr(car list)))',或者更好的'(second(first list))''。 –