提取列表中的每个数字并重建列表?
我需要创建这个函数 flat
,它应该从输入列表中重新收缩一个新列表(但在这里,输入列表内部可以有一个嵌套列表)
: (A (B (C) D) A) 的平铺是 (ABCDA)
我的算法如下,不确定是否正确:
- 检查列表是否为空:如果不是,则继续;如果是,done -- 返回空列表
- 如果列表长度为 1,done -- 返回列表
- 如果列表长度大于 1,我现在该怎么办? (我可以使用
car
和cdr
来提取列表,但无论哪种情况,我怎样才能让它递归地将列表提取到最后,我正在考虑使用追加以在之后重新构建列表。)
任何帮助/提示将不胜感激。
I need to create this function flat
that's supposed to re-contract a new list from the input list (but here, the input list can have a nested list inside):
ex. flat of (A (B (C) D) A) is (A B C D A)
My algorithm is the following, not sure if it's correct:
- Check if the list is empty: if not, go on; if yes, done -- return the empty list
- If the list has length 1, done -- return the list
- If list has length more than 1, what do I do now? (I can use
car
andcdr
to extract the list, but in either case, how can I make it recursively extract the list to the end, and I'm thinking use append to re-construct the list after.)
Any help/hints would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
提示是,如果列表不为
null?
,则不应关注传入flat
的列表的长度,而应检查是否列表的car
是一个列表本身或者只是一个原子。如果它本身是一个列表,您需要展平它,以及展平列表的cdr
。编辑:好吧,考虑两种不同情况下会发生什么,一种是使用
cons
,另一种是使用append
:在第一种情况下,你会得到一个平面列表,而在第二种情况下,你不会得到一个平面列表。然后您可能会尝试,
但如果
lst
的car
不是列表,则它将不起作用。您需要第三种情况,使用cond
,如下所示:The hint is that, if the list isn't
null?
, you shouldn't focus on the length of the list passed in toflat
, but instead check to see whether thecar
of the list is a list itself or just an atom. If it's a list itself, you want to flatten it, as well as flattening thecdr
of the list.EDIT: Well, consider what happens in two different cases, one where you use
cons
and one where you useappend
:In the first case, you get a flat list back, and in the second case, you don't get a flat list back. You might then try
but it won't work if the
car
oflst
isn't a list. You need a third case, usingcond
, like so:可能不是最优化的解决方案。也许你可以进一步改进它:
Might not be the most optimized solution. Probably you can improve it further: