Skip to content

Instantly share code, notes, and snippets.

@leafgarland
Created September 19, 2012 17:42
Show Gist options
  • Save leafgarland/3751025 to your computer and use it in GitHub Desktop.
Save leafgarland/3751025 to your computer and use it in GitHub Desktop.
Using Unfold to generate Fibonacci numbers
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