Monday 29 October 2012

Monads ... hang on, I'm thinking

So I'm thinking about monads and the shockingly non-functional try...catch...finally in C# and I what I want to do is something like this.
var results = Try(()=>doSomething()).Catch(()=>catchIt()).
     Catch(()=>YouveGotABiggerProblemNow()).Finally(()=>TidyUp());
I think that reads reasonably well and is a close approximation to a monad. The question in my mind at the moment is whether it will work as an extension to my already-created Exception Monad (MException if you're following me on Google Code) or whether I will need to create a new monad class, which would be annoying. In the latter case I would probably require an adapter, but that's okay because what do you think Bind() is supposed to be? LoL

Thursday 6 September 2012

LINQ group by

This one caught me out a couple of days ago. Recall to mind the good old IEnumerable . It's a good idea to act and code as if they can be traversed once only. As it happened we had some test code which iterated through two streams. Foolishly and without applying enough thought we wrote some linq which joined the two datastreams (ok so far) and then grouped them. Var a = from b in Bs From c in Cs Select new { b , c}; Var aa = from j in a group j by j.c.name; Oh dear. The group caused the Cs to be looped through one complete traversal for each element in Bs! Not good, because the stream was not restartable and so it went horribly wrong. The temporary solution is to turn Bs and Cs into lists and take the cross-product on the chin for now.

Friday 8 June 2012

Countdown - solver in C#

Countdown: presented with six integers they should be combined using the four arithmetic operators +, -, * and / to approach the target as closely as possible. Example code:
using System;
using System.Linq;
using System.Collections.Generic;
using NUnit.Framework;

namespace Test.Unit.Utils
{
    class NonIntegralDivisionResult:Exception {}

    [TestFixture]
    class Countdown
    {
        [Test]
        public static void CountdownTest1()
        {
            var operators = new Dictionary<string, Func<int, int, int>>
                            {
                                {"+", (a, b) => a + b},
                                {"-", (a, b) => a - b},
                                {"*", (a, b) => a*b},
                                {"/", (a, b) =>
                                         {
                                             var resAsDouble = a/(double) b;
                                             var dbl = (double) (a/b);
                                             if (resAsDouble != dbl) throw new NonIntegralDivisionResult();
                                             return a/b;
                                         }
                                    }
                            };
            var startNos = new[] {1, 5, 6, 7, 9, 10};
            var target = 127;

            var result = new Dictionary<int,List<string>>();

            foreach (var num1 in startNos)
                foreach (var op1 in operators)
                    foreach (var num2 in startNos.Except(new[] { num1 }))
                        foreach (var op2 in operators)
                            foreach (var num3 in startNos.Except(new[] { num1, num2 }))
                                foreach (var op3 in operators)
                                    foreach (var num4 in startNos.Except(new[] { num1, num2, num3 }))
                                        foreach (var op4 in operators)
                                            foreach (var num5 in startNos.Except(new[] { num1, num2, num3, num4 }))
                                                foreach (var op5 in operators)
                                                    foreach (var num6 in startNos.Except(new[] { num1, num2, num3, num4, num5 }))
                                                    {
                                                        try
                                                        {
                                                            var value = op5.Value(op4.Value(op3.Value(op2.Value(op1.Value(num1, num2), num3), num4), num5), num6);
                                                            var name = String.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}", num1, op1.Key, num2, op2.Key, num3, op3.Key, num4, op4.Key, num5, op5.Key, num6);
                                                            var key = Math.Abs(value - target);
                                                            if(result.ContainsKey(key)) result[key].Add(name);
                                                            else result.Add(key, new List{name});
                                                        }
                                                        catch(DivideByZeroException) {}
                                                        catch(NonIntegralDivisionResult) {}
                                                    }

            var output = result.OrderBy(kvp => kvp.Key).Take(25);
            foreach(var line in output)
                foreach(var value in line.Value)
                    Console.WriteLine("Key: {0} Value: {1}", line.Key, value);
        }
    }
}

Tuesday 15 May 2012

Linq makes creating dictionaries easy

Previously, I wrote example code that used one of my library functions to construct a dictionary when given a list or pair of list. Since the place of gainful employment moved to .NET 3.5 I have been able to write some truly linq-y code, and have observed many wonderful things, in particular the extension methods of IEnumerable. Check out ToDictionary( keyFn, valueFn) It's exactly what I was writing in my Functional.array.toDict function. Good work, Microsoft!