lambda - 汽车异常: () is not a pair

标签 lambda scheme lisp

我有一个必须制作的程序:

enter image description here

我已经能够编写一个程序,可以正确地判断树中是否存在某些东西,但如果树中不存在某些东西,它就会中断。 enter image description here

enter image description here 调试消息根本没有帮助。我唯一使用过 car 的地方是 3 个辅助功能。有人可以解释这意味着什么/我应该做什么吗?我一直在修补,但找不到解决办法。

以下是我目前所掌握的内容:

(define (val T)
    (car T)
)

(define (left T)
    (car (cdr T))
)

(define (right T)
    (car (cdr (cdr T)))
)

(define (tree-member-helper? V T)
    (if (not (null? (val T)))

        (if (< V (val T))
            (tree-member-helper? V (left T))
            (if (> V (val T))
                (tree-member-helper? V (right T))
                 #t
            )
        )
        '()
    )
)

最佳答案

在这一部分:

(not (null? (val T)))

您正在检查是否不为空。树的典型迭代会检查该值是否为空树。在您的情况下 () 因为节点 (1 () ()) 是一个值为 1 的节点,并且没有空树作为子节点。

首先,当您确定节点不为空时,您可以对其执行 carcdr (或调用执行此操作的函数)。

现在,为什么我们期望 caddr 在不进行检查的情况下工作,您可能会问。好吧,如果您发送像 '(1 (2) (3)) 这样的无效树,它不会发送,并且您会收到类似的错误。您可以通过创建一个检查节点是否确实有效的函数来解决此问题:

(define (valid-node? node)
  (and (list? node)
       (= (length node) 3)
       (number? (car node))))

关于lambda - 汽车异常: () is not a pair,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46231138/

相关文章:

functional-programming - 函数式编程 : why pair as a basic constructed unit?

list - Simply Scheme Lisp 中的子集/子序列递归过程

c++ - 在 Qt5 中断开 lambda 函数

scheme - 在 Chez Scheme 中查找操作系统和机器类型

lisp - 为什么需要在mapcar里面使用symbol-value来赋值?

list - Lisp 中的列表问题

scheme - 数据导向编程 SICP

java - Lambda 作为 Java 中带有参数和原语的方法

c# - Entity Framework 从 SQL Server View 返回损坏/交换数据

java - 将 Java Stream 过滤为 1 个且仅 1 个元素