list - MIT Scheme Expression append 的替代形式

标签 list filter scheme append cons

我目前正尝试在期中练习中解决一个问题。该问题要求我编写一个表达式来追加两个列表(让我们称它们为 list1 和 list2),并且 list2 必须追加到 list1 的末尾。 在此任何时候都不能使用函数append。我可能使用的是consfilteraccumulatemap、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

上述解决方案使用了condnull?conscarcdr。如果您不能使用这些中的任何一个并且您仅限于问题中的过程,请试试这个(假设 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 

上述解决方案只使用了accumulatecons,正如问题中所要求的那样。这个想法是:遍历第一个列表,逐个元素地重新创建它,直到列表用完——此时,下一个元素将是第二个列表。

关于list - MIT Scheme Expression append 的替代形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13437235/

相关文章:

java - 将构造函数与 Integer 一起使用

list - Haskell 中 [String] 的模式匹配

python - Pandas :按集合中包含的字段过滤

css - Internet Explorer CSS 属性 "filter"忽略溢出 :visible

ruby - 寻找 "real"使用延续的例子

scheme - Scheme中可变参数映射函数的实现

python - 查找列表中相差 1 的元素

C# 排序列表,逻辑比较

filter - 管道和过滤器

macros - SICP:可以或在 lisp 中定义为没有 gensym 的句法转换吗?