Created
September 19, 2012 17:42
-
-
Save leafgarland/3751025 to your computer and use it in GitHub Desktop.
Using Unfold to generate Fibonacci numbers
This file contains 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
var fibNumbers = InfiniteUnfold( | |
p => Tuple.Create(p.Item1, Tuple.Create(p.Item2, p.Item1 + p.Item2)), | |
Tuple.Create(1, 1)) | |
.Take(50); | |
public IEnumerable<T> InfiniteUnfold<T, TResult>( | |
Func<TResult, Tuple<T, TResult>> generator, | |
TResult seed) | |
{ | |
var next = seed; | |
while (true) | |
{ | |
var pair = generator(next); | |
yield return pair.Item1; | |
next = pair.Item2; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment