using System; using System.Collections.Generic; namespace Mono.Rocks { public static class KeyValuePair { public static KeyValuePair? Just (TKey key, TValue value) { return new KeyValuePair (key, value); } } public static class Sequence { public static IEnumerable Unfoldr (TSource value, Func?> func) { return CreateUnfoldrIterator (value, func); } private static IEnumerable CreateUnfoldrIterator (TSource value, Func?> func) { KeyValuePair? r; while ((r = func (value)).HasValue) { KeyValuePair v = r ?? new KeyValuePair (); yield return v.Key; value = v.Value; } } } class Test { public static int Main () { IEnumerable x = Sequence.Unfoldr (10, b => b == 0 ? null : KeyValuePair.Just (b, b - 1)); int i = 10; foreach (int e in x) { Console.WriteLine (e); if (i-- != e) return 1; } return 0; } } }