将项目添加到列表末尾的“缺点"是什么? [英] what is the 'cons' to add an item to the end of the list?

查看:23
本文介绍了将项目添加到列表末尾的“缺点"是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将项目添加到列表末尾的典型方法是什么?

what's the typical way to add an item to the end of the list?

我有一个列表 (1 2 3) 并且想向它添加 4(其中 4 是评估的结果 (+ 2 2))

I have a list (1 2 3) and want to add 4 to it (where 4 is the result of an evaluation (+ 2 2))

(setf nlist '(1 2 3))  
(append nlist (+ 2 2))  

这表示 append 需要一个列表,而不是一个数字.我将如何做到这一点?

This says that append expects a list, not a number. How would I accomplish this?

推荐答案

您可以使用 append,但请注意,如果在循环中或在很长的列表中使用它,可能会导致性能不佳.

You could use append, but beware that it can lead to bad performance if used in a loop or on very long lists.

(append '(1 2 3) (list (+ 2 2)))

如果性能很重要,通常的习惯用法是通过前置来构建列表(使用 cons),然后 reverse(或 nreverse).

If performance is important, the usual idiom is building lists by prepending (using cons), then reverse (or nreverse).

这篇关于将项目添加到列表末尾的“缺点"是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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