方案 - 编写我自己的 append 会产生一个奇怪的结果 [英] SCHEME - Writing my own append produces a weird result

查看:29
本文介绍了方案 - 编写我自己的 append 会产生一个奇怪的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写自己的 append ,用于将元素附加到现有列表中.

I want to write my own append , for appending an element to an existing list .

我写了以下内容:

(define (appendElem llist elem)
    (if (null? llist)
        elem
        (cons (car llist) (appendElem (cdr llist) elem))))

但是当我这样做时:

(appendElem (list 1 2 30) 11)

我明白了:

(1 2 30 . 11)

所以问题是,为什么 (1 2 30 . 11) 而不是 (1 2 30 11) ?

So the question is , why (1 2 30 . 11) and not (1 2 30 11) ?

谢谢

固定:

(define (appendElem llist elem)
    (if (null? llist)
        (list elem)
        (cons (car llist) (appendElem (cdr llist) elem))))

推荐答案

想想你希望你的基本情况是什么.您只想要 elem,还是想要一个 list 和单个项目 elem?它们是有区别的.如果想要后者,您需要在代码中修复您的基本情况.

Think about what you want your base case to be. Do you want just elem, or do you want a list with the single item elem? There is a difference. If the want the latter, you will need to fix your base case in the code.

换句话说,您希望 (appendElem '() 42) 返回 42 还是 (42) ?仔细思考这个问题的答案,然后思考每个选择的后果是什么.

In other words, do you want (appendElem '() 42) to return 42, or (42)? Think carefully about the answer to that question, then think about what the consequence of each choice is.

顺便说一下,虽然您可以将 appendElem 实现为玩具,但您很快就会意识到该函数的运行时间为 O(n).所以不要使用这种方法构建列表!构建列表的标准方法是cons 项,然后反转 最终结果列表.

By the way, while you can implement appendElem as a toy, you'll soon realise that that function has O(n) runtime. So do not build lists using this approach! The standard way to build a list is to cons items to it, then reverse the final resulting list.

这篇关于方案 - 编写我自己的 append 会产生一个奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆