lisp - 如何在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)
解决方案
首先,您的COND
语法不正确。的语法COND
是:
(cond
(condition1 result1...)
(condition2 result2...)
...
)
条件和结果的每个组合都应该在一个列表中。你正确地为T
条件做,但不是为(null list1)
条件。它应该是:
(cond
((null list1) unknown)
(t (color (cdr listoflist)))
)
但是您的功能逻辑对于您想要做的事情是完全错误的。
首先,函数不应该有多个参数。它应该只需要一个list
参数。
其次,您需要映射列表以递归处理每个元素。
第三,您需要引用unknown
才能按字面意思返回。
第四,在输入中,一个空列表应该是nil
or ()
, 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))
推荐阅读
- java - java.lang.UnsupportedOperationException: JsonObject - 不知道为什么
- javascript - 在本机反应中将数据从数组绑定到 TextInput
- java - 是否可以编写一个算法,采用二叉树 T 并返回一个表示 T 高度的整数值
- c - 如何在 c 中使用 bsearch 在结构中搜索数组
- python-3.x - Python如何区分参数是否为默认参数?
- reactjs - 切换组件不更新视图
- c# - 将资源添加到 Xamarin.Forms NuGet
- r - 为什么在批量调用中将路径写入我的ui
- php - 如何通过 PHP 中的 URL 更新数据库中的数据
- flutter - 升级到 Android X 后的 Firebase 问题