Created
January 28, 2011 22:44
-
-
Save proger/801168 to your computer and use it in GitHub Desktop.
question
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- generate an infinite sequence of sign alternating numbers | |
| -- how to make it really infinite so foldl doesn't take away the laziness of the evaluation? | |
| alternating count = foldl (\x (a,b) -> x ++ [a,b]) [] $ take count [(x,y) | x <- [1..], let y = negate x] | |
| -- out: | |
| [1,-1,2,-2,3,-3,4,-4,5,-5,6,-6,7,-7,8,-8,9,-9,10,-10] | |
| -- variants: | |
| -- using foldr | |
| alternating = foldr (\(a,b) x -> [a,b] ++ x) [] [(x,y) | x <- [1..], let y = negate x] | |
| -- concatenating list of lists | |
| alternating = concat [[x,y] | x <- [1..], let y = negate x] |
Author
Thanks for the hint!
hs> let alternating = concat [[x,y] | x <- [1..], let y = negate x]
hs> take 10 alternating
[1,-1,2,-2,3,-3,4,-4,5,-5]
^^ i wanted this :)
OK, you're welcome :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-- I like this one more :)
alternating count = concat $ take count [[x,y] | x <- [1..], let y = negate x]