首页 > 解决方案 > 如何在lisp中递归检查列表是否为空?

问题描述

我有一个叫做:

(defun color ( list1 list2 list3 list4 list5 listoflist))

(defun color (list1 list2 list3 list4 list5 listoflist)                           
    (cond 
        (null list1) 'unknown )
        (list (list1, list2 list3 list4 list5 lisoflist))
        (null list2) 'unknown)
          (list (list1 list2 list3 list4 list5 listoflist)

         (null list3) 'unknown )
        (null list4) 'unknown) 
        (null list5) 'unknown )

        (T (cons (car list1) (color (cdr list1) list2)))    ; recursively tring to replace with unknow if any of the lis tis empty and print the resulte ouptput
    )
)

如果输入是:(color null '(3 4 5) null) '(3 5 8) null)) 它应该产生(unknown (3 4 5) unknown (3 4 5) unknown)

标签: lisp

解决方案


首先,您的COND语法不正确。的语法COND是:

(cond
    (condition1 result1...)
    (condition2 result2...)
    ...
)

条件和结果的每个组合都应该在一个列表中。你正确地为T条件做,但不是为(null list1)条件。它应该是:

(cond
    ((null list1) unknown)
    (t (color (cdr listoflist)))
)

但是您的功能逻辑对于您想要做的事情是完全错误的。

首先,函数不应该有多个参数。它应该只需要一个list参数。

其次,您需要映射列表以递归处理每个元素。

第三,您需要引用unknown才能按字面意思返回。

第四,在输入中,一个空列表应该是nilor (), not null。这是测试列表是否为空的函数的名称。

(defun color-recurse (thing)
  (cond ((null thing) 'unknown)
        ((listp thing) (mapcar #'color-recurse thing))
        (t thing)))

(defun color (&rest things)
  (color-recurse things)) 

(color nil '(3 4 5) '(nil) '(3 5 8) '(nil))

输出:

(unknown (3 4 5) (unknown) (3 5 8) (unknown))

推荐阅读