【问题标题】:Problem about finding the same number of a given number in list LISP关于在列表 LISP 中查找给定数字的相同数字的问题
【发布时间】:2021-04-15 03:42:31
【问题描述】:

所以我试图接受两个参数,一个列表和一个数字,当且仅当数字等于列表中的任何元素时才返回 true

(defun find-num(a z)
    (if (= z (car a)) (write t))
    (if (not(= z (car a))) (find-num (cdr a)) )
    (if (not(= z (car a))) (write f) )
    )

(find-num '(1 2 3 4 5) 5)

所以我假设代码会执行这些步骤 如果 z 等于 a ,则返回 true, 如果 z 不等于 a ,则写入 f (返回 false )或跳转到递归函数,该函数在其余列表中查找数字,直到找到相同的数字

但是,我收到了这样的错误

VAL/APPLY: Too few arguments (1 instead of at least 2) given to
      FIND-NUM

我不确定是哪一部分搞砸了

我尝试使用 cond 语句,但也收到了同样的错误

(defun find-num(a z)
    (cond
    ( (= z (car a)) (write t) )
    ( (not(= z (car a))) (find-num (cdr a)) ) 
    ( (not(= z (car a))) (write f) )
        )
    )

(find-num '(1 2 3 4 5) 5)

【问题讨论】:

    标签: lisp common-lisp


    【解决方案1】:

    错误信息很清楚,不是吗?

    提供给 FIND-NUM 的参数太少(1 个而不是至少 2 个)

    您正在使用一个参数调用函数FIND-NUM,但该函数需要两个。您的函数具有参数az。那是两个。但是你的递归调用是(find-num (cdr a))。这只是一个论点:(cdr a) 的值。

    另一个问题:f 不是 Lisp 中 false 的值。 f 是一个未定义的变量。评估 (not t) 以查看 Lisp 中的 false 值究竟是什么。

    CL-USER > (not t)     
    

    结果可能是什么?

    接下来你需要检查你的函数是否返回正确的结果。

    【讨论】:

    • 谢谢,我找到了问题,我自己粗心的错误,我应该把(find-num (cdr a) z)。
    • (not t) 与 nil 相同,所以我猜我可以用 nil 或 (print () ) 替换它
    • Lisp 编译器将为您替换 (not t)nil;但无论如何,这样做的一个很好的理由是保持代码中没有这样的冗长。
    • 当然,我想我会把它留空
    【解决方案2】:
    (defun find-num (arr num)
      (cond ((null arr) nil)              ;; if no arr element equals num -> nil
            ((= (car arr) num) t)         ;; if first element of array equals num -> t
            (t (find-num (cdr arr) num)))) ;; otherwise search in rest of arry for num
    

    【讨论】:

    • 我猜这也有效: (defun find-num(a z) (cond ( (= 0 (length a)) (write ()) ) ( (= z (car a)) (write #\t) ) ; 否则循环 (t (find-num (cdr a) z)) ) ) (find-num '(1 2 3 4) 22)
    • 你不需要write - 让函数返回值(在普通的lisp中你不需要显式return)。
    • (= 0 (length a) 实际上是(null a) - null 会更有效率。 #\t 是字母“t”而不是对象 t(真)所以要小心!
    • 如果你真的想使用write,那么你必须使用(write t)而不是(write #\t)
    • (type-of t) => BOOLEAN, (type-of #\t) => STANDARD-CHAR - 但在条件句中,#\t 被视为t,因为所有非nil 都被视为t .但它不是布尔值 - 总有一天它会咬你。 (eq #\t t) => NIL 和 (eql #\t t) => NIL
    猜你喜欢
    • 1970-01-01
    • 2023-01-07
    • 2015-11-22
    • 1970-01-01
    • 2020-09-18
    • 2018-01-02
    • 2012-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多