black
black

Reputation: 11

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

Upvotes: 1

Views: 519

Answers (2)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84529

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]

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476544

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:

[ 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 (*) [1..] $ cycle [1, -1]

Or a solution where we iterate over functions:

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

Upvotes: 10

Related Questions