【问题标题】:Unbound Variable on Function Name函数名称上的未绑定变量
【发布时间】:2010-12-05 22:37:24
【问题描述】:

我正在用 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)))
      )
)

函数返回错误“未绑定变量:LLENGTH”,我不明白为什么或如何修复它。 有什么建议么 ?

【问题讨论】:

  • 是的,请重新格式化代码,使其可读

标签: variables lisp common-lisp


【解决方案1】:

您的代码中有多个错误。

首先,list 函数创建新列表,而不检查它是否是一个列表。您需要的功能是listp - 最后的“p”表示“谓词”。

其次,(progn (+ (llength (first L)) 1) (llength (rest L)) 不会增加计数器。 progn 一个一个地执行表达式并返回最后一个表达式的结果,其他的结果就被扔掉了。 progn 主要用于副作用。您实际需要的是添加所有三个组件:1 表示找到的列表,将函数应用于第一个元素的结果以及应用于其余元素的结果。所以,这一行必须是:

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

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

【讨论】:

    【解决方案2】:

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

    (function name (parameters))
    

    也许您只是在输入:

    function name (parameters)
    

    这样做会让您收到您收到的错误,因此请务必将您的整个陈述包含在括号中。

    【讨论】:

      【解决方案3】:
      (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
      

      【讨论】:

        猜你喜欢
        • 2014-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-04
        • 1970-01-01
        • 1970-01-01
        • 2021-02-08
        • 2016-04-27
        相关资源
        最近更新 更多