【发布时间】:2019-10-17 16:53:05
【问题描述】:
我正在尝试回答这个编码问题,但我没有任何运气来解决这个问题。我不知道如何递归地找到子列表。
例如:(max_sub_list '(1 (1 2 3 4) (1 2 3))) => (1 2 3 4)
这是我的代码现在的样子,我需要一些帮助。
(defun max_sub_list (L)
(if (>= (my-len (car L)) (my-len (cdr L)))
(max_sub_list (cdr L))
(return (my-len (L)))))
my-len 函数:
(if L
(1+ (my-len (cdr L)))
0)
使用我的原始代码,我遇到了问题CDR: 1 is not a list
我对 Lisp 很陌生,所以非常感谢任何帮助
更新:我决定使用两个函数来完成这个任务。这是我现在得到的:
(defun compare (a b)
(cond
((> (my-len a) (my-len b)) a)
(t b))
)
(defun max_sub_list (a)
(compare(car(a) (max_sub_list(cdr(a)))))
)
更新 2:运行但不正确。
(defun compare (a b)
(cond
((> (my-len a) (my-len b)) a)
(t b))
)
(defun max_sub_list (a)
)
;;(write (compare '(1 2 3 4 5) '(1 2 3 4)))
(write (max_sub_list '(1 (1 2 3 4) (1 2 3))))
比较方法返回正确的值:(1 2 3 4 5)
max_sub_list 方法现在返回 nil,因为其中没有任何内容。我需要使用列表中的car 与列表中的cdr 中的max_sub_list 来调用谓词(比较)。
【问题讨论】:
-
1是atom而不是list所以没有cdr。您需要检查给定列表的当前元素是否是一个列表。 -
(car (a))不可能是正确的,因为a不是函数,请参阅 Rainer 的回答。 -
那么如何比较列表的第一个值和 max_sub_list 中的列表的第二个值呢??
-
我想我不明白你的意思。您能否以至少在没有语法错误的情况下运行的版本提供所有代码?据我所知,如果初始列表包含原子,您的代码仍然会失败。
-
查看我实现的代码更新。我还添加了我需要的功能
max_sub_list来做
标签: recursion common-lisp