With iterate
Perhaps a more elegant way to do this, is by using iterate :: (a -> a) -> a -> [a]
with a function that generates each time the next item. For instance:
solution = iterate nxt 0
where nxt i | i > 0 = -i
| otherwise = 1-i
Or we can inline this with an if
-then
-else
:
solution = iterate (\i -> if i > 0 then -i else 1-i) 0
Or we can convert the boolean to an integer, like @melpomene says, with fromEnum
, and then use this to add 1
or 0
to the answer, so:
solution = iterate (\i -> fromEnum (i < 1)-i) 0
Which is more pointfree:
import Control.Monad(ap)
solution = iterate (ap subtract (fromEnum . (< 1))) 0
With (<**>)
We can also use the <**>
operator from applicate to produce each time the positive and negative variant of a number, like:
import Control.Applicative((<**>))
solution = 0 : ([1..] <**> [id, negate])
iterate (\i -> fromEnum (i < 1) - i)
? – Chlorenchyma