Search And Destroy

Look out honey, ’cause I’m using technology!

Archive for the ‘Fun with Continuations’ Category

On Mucking About

Posted by kilfour on January 12, 2011

Following up on this post, today, I got this test working :

public class Spike
{
    [Fact]
    public void NullIsStringThatSaysNull_When_Something_Is_Null()
    {
        Person person = null;

        var result =
            new SomeNullIsNullString<Spike>(this)
                .Do(x => person)
                .Do(x => x.Adress)
                .Do(x => x.Postcode);

        Assert.Equal("null", result.ToString());
    }

    [Fact]
    public void NullIsStringThatSaysNull_When_Something_Is_Null_Stops_Execution()
    {
        Person person = null;

        var result =
            new SomeNullIsNullString<Spike>(this)
                .Do(x => person)
                .Do(x => x.TriesToGetAddressButThrows())
                .Do(x => x.Postcode);

        Assert.Equal("null", result.ToString());
    }

    [Fact]
    public void NullIsStringThatSaysNull_Everyting_Exists()
    {
        var person =
            new Person
            {
                Adress = new Adress { Postcode = "2000" }
            };

        var result =
            new SomeNullIsNullString<Spike>(this)
                .Do(x => person)
                .Do(x => x.Adress)
                .Do(x => x.Postcode);

        Assert.Equal("2000", result.ToString());
    }
}

Using this simple model :
public class Person
{
    public Adress Adress;

    public Adress TriesToGetAddressButThrows()
    {
        throw new Exception();
    }
}

public class Adress
{
    public string Postcode;
}

Posted in Fun with Continuations | Leave a Comment »

On QuickNet.Future.MonadicComputations

Posted by kilfour on September 30, 2010

namespace QuickNet.Future.MonadicComputations
{
    public class Spike
    {
        public Thing Generate()
        {
            IEnumerator<IState> stateMachine = GenerateThing();
            return stateMachine.Apply<Thing>().Value;
        }

        public class Thing
        {
            public int One { get; set; }
            public int Two { get; set; }
            public Thing InnerThing { get; set; }
        }

        private int currentTreeDepth;
        private const int maximumTreeDepth = 3;
        private IEnumerator<IState> GenerateThing()
        {
            if (currentTreeDepth++ > maximumTreeDepth)
                yield return new StateResult<Thing>(null);

            yield return
                StateResult.Create(
                    new Thing
                    {
                        One = GenerateInt().Apply<int>().Value,
                        Two = GenerateInt().Apply<int>().Value,
                        InnerThing = GenerateThing().Apply<Thing>().Value
                    });
        }

        private IEnumerator<IState> GenerateInt()
        {
            yield return StateResult.Create(new IntGenerator(5, 10).GetRandomValue());
        }
    }
}

Having your test run hanging around as a state machine (that you can re-execute) is incredibly usefull.
As you can see I’m thinking about applying this stuff to QuickGenerate first, without changing the GeneratorRepository interface ofcourse.
I reckon using it there will get rid of a lot of (repetitive) classes/methods in the Meta/Uber namespace.

Posted in Fun with Continuations | Leave a Comment »

On “Encoding monadic computations in C# using iterators”

Posted by kilfour on September 28, 2010

Which is a paper I came across earlier today.

Bit of a long text, but to wet your appetite I’ll highlight a sample.

This :

Console.WriteLine(ReadIntAndMultiplyByTen("5").Apply<int>());

Results in :
Enter a number : Got a valid number !
50

This :
Console.WriteLine(ReadIntAndMultiplyByTen("5s").Apply<int>());

Results in :
Enter a number : none

Let’s look at the ReadIntAndMultiplyByTen method and helpers :
private IEnumerator<IOption> ReadIntAndMultiplyByTen(string s)
{
    var optionStep = ReadInt(s);
    yield return optionStep;
    yield return MultiplyByTen(optionStep);
}

private OptionStep<int> ReadInt(string s)
{
    Console.Write("Enter a number : ");
    return ParseInt(s).AsStep();
}

private OptionResult<int> MultiplyByTen(OptionStep<int> optionStep)
{
    Console.WriteLine("Got a valid number !");
    return OptionResult.Create(optionStep.Value * 10);
}

private Option<int> ParseInt(string s)
{
    int res = 0;
    if (int.TryParse(s, out res))
        return new Some<int>(res);
    return new None<int>();
}

And here’s the interesting bit :
When we pass an invalid int to the ReadInt function the MultiplyByTen function is never evaluated.

Composition
Supposing :

private IEnumerator<IOption> TryCalculate(string s1, string s2) 
{
    var step1 = ReadIntAndMultiplyByTen(s1).Apply<int>().AsStep();
    yield return step1;
    var step2 = ReadIntAndMultiplyByTen(s2).Apply<int>().AsStep();
    yield return step2;
    yield return OptionResult.Create(step1.Value + step2.Value);
}

Then :


Console.WriteLine(TryCalculate("5", "3").Apply<int>());

Enter a number : Got a valid number!
Enter a number : Got a valid number!
80


 Console.WriteLine(TryCalculate("5s", "3").Apply<int>());

Enter a number : none


Console.WriteLine(TryCalculate("5", "3s").Apply<int>());

Enter a number : Got a valid number!
Enter a number : none


Look ma, no null-checks !

Posted in C# Musings, Fun with Continuations | 1 Comment »

Fun with Continuations : When Dealing with Legacy Data Access, Part II

Posted by kilfour on June 18, 2010

public class InsertMeetingHolidayQuery : NonQuery<Holiday>
{
    protected override string ProcedureName { get { return "InsertMeetingHolidays"; } }
    protected override void ExecuteImplementation(Holiday holiday)
    {
        BuildCommand()
            .Add(Parameter.Named("p_Date").In(holiday.HolidayDate))
            .Add(Parameter.Named("p_Description").In(holiday.Description))
            .Add(Parameter.ResultOut())
            .Execute();
    }
}

public class GetAllHolidaysQuery : Query<Holiday>
{
    protected override string ProcedureName { get { return "GetMeetingHolidays"; } }
    protected override IEnumerable<Holiday> ExecuteImplementation()
    {
        return
            BuildCommand()
                .Add(Parameter.Named("p_year").In(DateTime.Now.Year.ToString()))
                .Add(Parameter.Named("holidays_info").Out())
                .Add(Parameter.ResultOut())
                .FromReader(reader =>
                            new Holiday(DateTime.Parse(reader.GetValue(1).ToString()), reader.GetValue(2).ToString())
                                {
                                    Surr = Int32.Parse(reader.GetValue(0).ToString()),
                                    CreateDate = DateTime.Parse(reader.GetValue(3).ToString()),
                                    CreateBy = reader.GetValue(4).ToString(),
                                    LastModificationDate = DateTime.Parse(reader.GetValue(5).ToString()),
                                    LastModifiedby = reader.GetValue(6).ToString()
                                });
    }
}

Posted in C# Musings, Fun with Continuations | Leave a Comment »

Fun with Continuations : When Dealing with Legacy Data Access

Posted by kilfour on June 16, 2010

IEnumerable<Holiday> holidays = SP_GETALL
    .CreateCommand()
    .Add(Parameter.Named("p_year").In(DateTime.Now.Year.ToString()))
    .Add(Parameter.Named("holidays_info").Out())
    .Add(Parameter.ResultOut())
    .FromReader(reader =>
                new Holiday(DateTime.Parse(reader.GetValue(1).ToString()), reader.GetValue(2).ToString())
                    {
                        Surr = Int32.Parse(reader.GetValue(0).ToString()),
                        CreateDate = DateTime.Parse(reader.GetValue(3).ToString()),
                        CreateBy = reader.GetValue(4).ToString(),
                        LastModificationDate = DateTime.Parse(reader.GetValue(5).ToString()),
                        LastModifiedby = reader.GetValue(6).ToString()
                    });

Posted in C# Musings, Fun with Continuations | Leave a Comment »

Fun with Continuations : Whilst Avoiding WinForms DataGridView Hell

Posted by kilfour on April 19, 2010

new DataGridView<ProductDto>(productsDataGridView)
    .AsText(productDto => productDto.Id, col => col.Visible = false)
    .AsCheckBox(productDto => productDto.Validated, ValidatedCheckboxClickedHandler)
    .FormatRow(productDto => productDto.ProductCode == 2, row => row.DefaultCellStyle.BackColor = Color.LightGreen)
    .FormatRow(productDto => productDto.ProductCode != 2, row => row.DefaultCellStyle.BackColor = Color.LightGray)
    .Initialize();

Posted in C# Musings, Fun with Continuations | 1 Comment »

Fun with Continuations : in QuickNet.Generators

Posted by kilfour on April 17, 2010

From the google group :

new GeneratorRepository() 
	.With<double>(mi => mi.Name.ToLower().Contains("price"), val => Math.Round(val, 2)) 
	.With<double>(mi => mi.DeclaringType == typeof (Node), val => Math.Round(val, 1)) 
	.With<double>(val => Math.Round(val, 5)) 
	.With(new IntGenerator(42, 42)) 
	.With(mi => mi.DeclaringType == typeof (Node), new IntGenerator(43, 43)) 
	.With<Item>() 
	.With(new NullGenerator<Item>()) 
	.With<Node>(gen => gen.Ignore(t => t.YetAnotherLeaf)) 
	.With<Node, DerivedNode>() 
	.Random<Root>(gen => gen.For(t => t.Leaf, new ConstantGenerator<int>(5)));

Posted in C# Musings, Fun with Continuations | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.