展平一次程序 [英] Flatten once procedure
问题描述
我在编码一次将列表变平的过程时遇到了一些麻烦,即
(flatten-once '((b) (c f) ((d)(e))))
将产生'(b c f (d) (e)))
.我检查了一些有关标准展平过程如何工作的资料,但是它实现了我需要使用的intermediate student with lambda
语言形式中未包含的功能.据我了解,foldr
会有所帮助,并且已经成功做到了
I'm having a bit of a struggle with coding a procedure that flattens a list once, i.e
(flatten-once '((b) (c f) ((d)(e))))
would produce '(b c f (d) (e)))
. I checked up on a few sources on how the standard flatten procedure works but it implements functions that are not included in the intermediate student with lambda
language form I'm required to use. As far as I have it figured out a foldr
would be somewhat helpful and have managed to get this
(define (flatten-once lst)
(cond
[(empty? lst) lst]
[else
((foldr cons (first (rest lst)) (first lst)))]))
返回'(b c f)
,所以我想它会使列表的一部分变平.我尝试通过递归继续定义,但这只会产生错误,因此我想我缺少了一些东西.
which returns '(b c f)
, so I guess it flattens part of the list. I tried continuing the definition through recursion but that just gives errors, so I guess I'm missing something.
推荐答案
建议的代码过于复杂,抵制了在各处使用折叠的诱惑,它们并不能解决所有问题-我之所以这样说是因为我已经看过其他您的问题,而且经常会不必要地调用foldr
或foldl
.一个简单的append
就能解决问题:
The proposed code is overly complicated, resist the temptation to use folds everywhere, they're not the answer to everything - I say this because I've seen other of your questions and frequently, there's an unnecessary call to foldr
or foldl
. A simple append
will do the trick:
(define (flatten-once lst)
(apply append lst))
它按预期工作:
(flatten-once '((b) (c f) ((d)(e))))
=> '(b c f (d) (e))
如果输入列表包含非列表元素,则需要做更多的工作.要格外小心,我们可以这样做:
If the input list contains elements which are not lists, then a bit more of work needs to be done. To be extra-careful, we can do this:
(define (flatten-once lst)
(apply append
(map (lambda (e) (if (cons? e) e (list e)))
lst)))
现在它适用于此类输入,请注意元素a
已添加到列表中.另一个选择是从列表中删除,如果这样做更有意义,则在上面的代码中将(list e)
替换为'()
.
Now it'll work for inputs such as this one, noticing that the element a
was added to the list. Another alternative would be to delete it from the list, if that makes more sense then replace (list e)
with '()
in the code above.
(flatten-once '(a (b) (c f) ((d)(e))))
=> '(a b c f (d) (e))
最后,按照@Alex的精神,也可以使用foldr
编写第二个变体:
Finally, in the spirit of @Alex's answer, this second variant can also be written using foldr
:
(define (flatten-once lst)
(foldr (lambda (e acc)
(append (if (cons? e) e (list e)) acc))
'()
lst))
这篇关于展平一次程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!