我目前正尝试在期中练习中解决一个问题。该问题要求我编写一个表达式来追加两个列表(让我们称它们为 list1 和 list2),并且 list2 必须追加到 list1 的末尾。 在此任何时候都不能使用函数append。我可能使用的是cons、filter、accumulate 、map、list-ref 和 umerate-interval。我尝试了各种形式的解决方案,例如
(cons list1 list2)
(filter list? (map list (cons list1 list2)))
(list list1 list2)
(map list (list list1 list2))
我花了 2 天时间试图找到解决方案,但无济于事。如果有人能够在正确的方向上指导我,甚至为我提供某种形式的帮助,我将不胜感激。
此外,如果我在代码格式或提问时的举止方面有错误地遵循了某些协议(protocol),我深表歉意,因为我是该网站的新手。谢谢。
最佳答案
因为这是作业,我不能直接给你答案。相反,我会给你一些提示,你可以在空白处找到你自己问题的答案。这是实现 append
的标准方法:
(define (my-append l1 l2)
(cond (<???> ; if the first list is null
<???>) ; then return the second list
(<???> ; if the second list is null
<???>) ; then return the first list
(else ; otherwise `cons`
(cons <???> ; the first element of the first list
(my-append <???> l2))))) ; process the rest of the first list
上述解决方案使用了cond
、null?
、cons
、car
和cdr
。如果您不能使用这些中的任何一个并且您仅限于问题中的过程,请试试这个(假设 accumulate
被定义为向右折叠):
(define (my-append l1 l2)
(accumulate
<???> ; what should be used for sticking list elements together?
<???> ; what should we return if the list being traversed is empty?
<???>)) ; this is the list that we want to traverse
上述解决方案只使用了accumulate
和cons
,正如问题中所要求的那样。这个想法是:遍历第一个列表,逐个元素地重新创建它,直到列表用完——此时,下一个元素将是第二个列表。
关于list - MIT Scheme Expression append 的替代形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13437235/