MIT Scheme表达式的append替代形式

3

我目前正在尝试解决一道关于中期练习的问题。这个问题要求我编写一个表达式来将两个列表(我们称之为list1和list2)连接起来,其中list2必须附加到list1的末尾。在整个过程中不能使用函数append。 我可以使用consfilteraccumulatemap、list-ref和inumerate-interval。 我已经尝试了各种形式的解决方案,例如:

(cons list1 list2)

(filter list? (map list (cons list1 list2)))

(list list1 list2)

(map list (list list1 list2)) 

我已经花了两天时间尝试找到解决方案,但是一无所获。如果有人能够指导我正确的方向,或者提供任何形式的帮助,我将不胜感激。

另外,如果我的代码格式或问题的提问方式存在某些错误,请谅解我是新手。谢谢。

1个回答

2
因为这是一份作业,我不能直接给你答案。相反,我会给你一些提示,你可以通过填空找到自己问题的答案。这是实现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,正如问题所要求的那样。其思路是:遍历第一个列表,逐个元素重新创建它,直到列表用尽 - 在这一点上,下一个元素将是第二个列表。

好的,这实际上并不是作业,因为它没有截止日期,也不会被评分。这只是一份旧考试的练习题,除非在这里这算作作业...?无论如何,你给了我一个很好的想法,我很感激。 - CodeRook
@Gabe 太好了!即使这不是作业,你自己找到答案会更有用。如果这个答案对你有帮助,请不要忘记通过点击左侧的复选标记来接受它。 - Óscar López
已将两个解决方案都运行成功,但我更喜欢你的第二个解决方案,因为它更简短,更符合问题的要求。非常感谢! - CodeRook

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接