The above answer does not quite work .... and does not have the same signature as Haskell scanl .... basically it is an extension of the linq "aggregate" idea ... I think this is better suited to the Haskell implementation
public static IEnumerable<TResult> Scanl<T, TResult>( this IEnumerable<T> source, TResult first, Func<TResult, T, TResult> combine) { using (IEnumerator<T> data = source.GetEnumerator()) { yield return first; while (data.MoveNext()) { first = combine(first, data.Current); yield return first; } } }
Using
[TestMethod] public void Scanl_Test() { var xs = new int[] { 1, 2, 3, 4, 5, 6, 7 }; var lazyYs = xs.Scanl(0, (y, x) => y + x); var ys = lazyYs.ToArray(); Assert.AreEqual(ys[0], 0); Assert.AreEqual(ys[1], 1); Assert.AreEqual(ys[2], 3); Assert.AreEqual(ys[3], 6); Assert.AreEqual(ys[4], 10); Assert.AreEqual(ys[5], 15); Assert.AreEqual(ys[6], 21); Assert.AreEqual(ys[7], 28); }
user2088029 May 09 '13 at 10:08 a.m. 2013-05-09 10:08
source share