Thursday, August 8, 2013

Infinite lists and function composition in C#

Last night I was critical of the way that F# handled lists.  This morning, I decided to back up my critique by implementing the functionality I was talking about in C#.  I have put a simplified version of it in a gist.  This was easily one of the most rewarding mornings of coding I have had in a long time.

First, I created FunctionalList<T>, which can be initialized with a lambda expression.  So, where Haskell might have the following:

    let squares = [x | a <- [3,6..27], let x = a * a]
    show squares

I can now do the following in C#:

    FunctionalList<int> squares = HigherOrderFunction<int, int>.Map
        a => a * a,
        FunctionalList.Series(3, 6, 27)
    [9, 36, 81, 144, 225, 324, 441, 576, 729]

So far, I have implemented the higher order functions Map, FoldLeft and FoldRight, as well as basic functionality for the lists such as Head, Tail, Take, Skip and Construct.  I can now do what I said F# should be able to do.  For the following Haskell expression:

    head $ map' (^2) [9,19..99999999]

I can write in C#:

    HigherOrderFunction<int, int>.Map
        x => x * x,
        FunctionalList.Series(9, 19, 99999999)

Granted, my C# version is syntactically clunky, but it returns immediately with the correct result.  It does not generate a huge in-memory list, and it works by composing the square function (x => x * x) over the function that returns the elements of the underlying series (x => x * 10 + 9).

So there.

No comments:

Post a Comment