Skip to content

Instantly share code, notes, and snippets.

@proger
Created January 28, 2011 22:44
Show Gist options
  • Select an option

  • Save proger/801168 to your computer and use it in GitHub Desktop.

Select an option

Save proger/801168 to your computer and use it in GitHub Desktop.
question
-- 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]
@vlprans
Copy link
Copy Markdown

vlprans commented Jan 28, 2011

-- I like this one more :)

alternating count = concat $ take count [[x,y] | x <- [1..], let y = negate x]

@proger
Copy link
Copy Markdown
Author

proger commented Jan 29, 2011

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 :)

@vlprans
Copy link
Copy Markdown

vlprans commented Jan 29, 2011

OK, you're welcome :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment