【问题标题】:Get element from list of list in lisp从lisp列表中获取元素
【发布时间】:2015-05-22 21:31:43
【问题描述】:

我是 lisp 的初学者。 我操作列表列表: ((name1, second) (name2, second2))

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

例如: 我的清单是: ((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

【问题讨论】:

  • @Bill 抱歉,我更改了变量的名称,但忘记了这个。 nodelist 是列表(参数)。
  • 当您使用正确的变量名时是否会给出错误消息?如果是这样:使用什么 lisp,以及如何调用函数?

标签: lisp elisp common-lisp


【解决方案1】:
  1. if 子句的顺序错误。
  2. 当字符串匹配时,您将使用下一个元素 (cdr) 而不是匹配的元素 (car)

这应该可行:

(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))))

【讨论】:

  • 该函数应该返回元素跟随匹配的元素,即(car (cdr (car list))),或者更好的(second (first list))
【解决方案2】:
 (defun get-element (list name)
    (cadr (assoc name list :test #'string=)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-04
    • 2023-03-24
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多