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

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

问题描述



我写了下面的内容:

 (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)
,而不是 >

> code>(1 2 30 11)


感谢

编辑:

$ b $ p

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $($) b $ b(list elem)
(cons(car llist)(appendElem(cdr llist)elem))))


解决方案

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



换句话说,是否需要(appendElem'( )42)返回 42 (42)?仔细想想这个问题的答案,然后考虑每个选择的结果。

顺便说一句,虽然你可以实现 appendElem 作为玩具,您很快就会意识到该函数具有O(n)运行时。所以不要使用这种方法建立列表!建立一个列表的标准方法是使用 cons 项目,然后 reverse 最终结果列表。


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

I've written the following :

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

But when I do this :

(appendElem (list 1 2 30) 11)

I get :

(1 2 30 . 11)

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

Thanks

EDIT:

Fixed :

(define (appendElem llist elem)
    (if (null? llist)
        (list elem)
        (cons (car llist) (appendElem (cdr llist) 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.

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.

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.

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

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