Skip to content

Instantly share code, notes, and snippets.

@WillNess
Last active December 16, 2015 00:28
Show Gist options
  • Select an option

  • Save WillNess/5347342 to your computer and use it in GitHub Desktop.

Select an option

Save WillNess/5347342 to your computer and use it in GitHub Desktop.
Can fold be used to create infinite lists? -- by pigworker Sep 6 '12 at 11:37 -- http://stackoverflow.com/a/12299223/849891
"A cheeky person can thus express any infinitary recursion as a non-recursive foldr
on an infinite list. E.g.,
foldr (\_ fibs -> 1 : 1 : zipWith (+) fibs (tail fibs)) undefined [1..]
(Edit: or, for that matter
foldr (\_ fib a b -> a : fib b (a + b)) undefined [1..] 1 1
which is closer to the definition in the question.)"
------
Prelude> let fact n = foldr (\k fact -> if k > n then 1 else k*fact) undefined [1..]
(0.00 secs, 528100 bytes)
Prelude> fact 5
120
(0.01 secs, 525032 bytes)
Prelude> let fact n = foldr (\_ fact k a -> if k > n then a else fact (k+1) (k*a) ) undefined [1..] 1 1
(0.00 secs, 525232 bytes)
Prelude> fact 5
120
(0.01 secs, 525168 bytes)
Prelude>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment