Last active
December 16, 2015 00:28
-
-
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
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
| "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