函数名称上的未绑定变量

时间:2010-12-05 22:37:25

标签: variables lisp common-lisp

我正在用Lisp编写一个程序(常见的lisp方言) 我希望程序计算列表中的子列表数量。 这就是我到现在所写的:

(defun llength (L)
      (cond 
          ((null L)   0)    
          ((list (first L)) (progn (+ (llength (first L)) 1) (llength (rest L))))    
          ((atom (first L)) (llength (rest L)))
      )
)

该函数返回错误“Unbound variable:LLENGTH”,我不明白为什么或如何解决它.. 有什么建议 ?

3 个答案:

答案 0 :(得分:2)

您的代码中有多个错误。

首先,list函数创建新列表,而不是检查它是否是列表。你需要的功能是listp - “p”在末尾意味着“谓词”。

其次,(progn (+ (llength (first L)) 1) (llength (rest L))不会增加反击。 progn逐个执行表达式并返回最后一个表达式的结果,其他结果将被抛出。 progn主要是副作用。你真正需要的是添加所有三个组件:1表示一个找到的列表,将函数应用于第一个元素的结果和应用于其余元素的结果。所以,这一行必须是:

((listp (first L)) (+ (llength (first L)) (llength (rest L)) 1))

可能存在更多错误,请小心正确缩进代码 - 这确实有助于减少它们。

答案 1 :(得分:2)

当您使用(defun function name (parameters))调用定义函数时,必须通过键入以下内容来调用该函数:

(function name (parameters))

也许您只是输入:

function name (parameters)

执行此操作会收到您收到的错误,因此请务必在括号中包含您的整个陈述。

答案 2 :(得分:0)

(defun llength (list)
  (cond 
    ((null list) 0)
    ((listp (first list))
     ;; 1 + the count of any sub-lists in this sub-list + the 
     ;; count of any sub-lists in the rest of the list.
     (+ 1 (llength (first list))
        (llength (rest list))))
    (t (llength (rest list)))))

测试:

> (llength '(1 2 3 4))
0
> (llength '(1 2 (3 4)))
1
> (llength '(1 2 (3 (4))))
2
> (llength '(1 2 (3 4) (5 6) (7 8) (9 (10 (11)))))
6