简体   繁体   English

获取位于初始列表偶数位置的元素列表

[英]Get the list of elements located in the even positions of initial list

The task is to use just one passthrough using foldr or foldl . 任务是仅使用foldrfoldl I use this decision: 我使用这个决定:

evenOnly = fst . foldr (\x (y1, y2) -> (y2, x:y1)) ([],[])

Pretty good for finite lists. 对于有限列表来说相当不错。 If I try evenOnly [1,2..] I'll got a fail. 如果我尝试evenOnly [1,2..]我将会失败。 I know it's because of suspended caclulations, but how can I otherwise split the list or how to pass additional information about list positions or something to the calculations which begin at the end of the list? 我知道这是由于挂起了caclulations,但是我如何才能拆分列表或如何将有关列表位置或其他内容的附加信息传递给从列表末尾开始的计算呢?

You can use a lazy pattern ~(x1, y2) : 您可以使用惰性模式 ~(x1, y2)

> let evenOnly = fst . foldr (\x ~(y1, y2) -> (y2, x:y1)) ([],[])
> take 20 $ evenOnly [1..]
[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40]

This is essentially the same as 这基本上与

> let evenOnly = fst . foldr (\x y -> (snd y, x:fst y)) ([],[])

which has the advantage of not forcing the pair constructor too early. 这样做的好处是不会过早强制配对构造器。 That is, the lambda above will produce the (,) constructor in its output before it demands y (the "recursive" result). 也就是说,上面的lambda会要求y 之前在其输出中生成(,)构造函数(“递归”结果)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM