简体   繁体   English

具有交替符号的Haskell无限列表

[英]Haskell infinite list with alternating signs

I try to generate a infinite list like this: 我尝试生成一个像这样的无限列表:

[1,-2,3,-4..]

with this code: 使用此代码:

[ m  | n <- [1..],m <- [n, -n]]

but this code reduplicate all numbers like this: 但是此代码将所有数字重新复制为:

[1,-1,2,-2..]

So i dont know what to do 所以我不知道该怎么办

You can group these as follows: 您可以将这些分组如下:

[[1, -2], [3, -4],..]

So we make tuples of i where i makes hops of two, and for such i , we yield i and -i-1 : 所以我们做的元组i在那里i做的两跳,和这样的i ,我们得到i-i-1

[ m  | n <- [1,3..], m <- [n, -n-1]]

then for example we can yield: 那么例如我们可以产生:

Prelude> take 10 [ m  | n <- [1,3..], m <- [n, -n-1]]
[1,-2,3,-4,5,-6,7,-8,9,-10]

Or we can write it as: 或者我们可以这样写:

[1, 3..] >>= \i -> [i, -i-1]

We can also work with zipWith : 我们还可以使用zipWith

zipWith (*) [1..] $ cycle [1, -1]

Or a solution where we iterate over functions: 或我们迭代功能的解决方案:

zipWith ($) (cycle [id, negate]) [1..]

A possibility: 一个潜在可能:

> x = concatMap (\i -> [i,-i-1]) [i | i <- [0..], even i]
> take 10 x
[0,-1,2,-3,4,-5,6,-7,8,-9]

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

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