Pages

Showing posts with label Functional Programming. Show all posts
Showing posts with label Functional Programming. Show all posts

Tuesday, April 19, 2011

CSpec

CSpec


It has been a long time since I posted something here. I have no free time to do my personal life and come to think of it there was nothing interesting to write about but the main reason is that I was just lazy :-). Since that time many things had changed for the better, first of all I took MS certification and passed (70-536). This was on my TODO list for at least a year now and there was always something better to do, but finally I got myself together and did it, but to my surprise I'm not an MCP :-( (I can still use the title but officially MS abandoned that title), so that's a slap to the face if you ask me.

The other cool thing is that recently Ive been doing a lot of ruby (started a company and got my hosting in rails) in my free time. Now I don't blog about that as I'm learning it so I can't provide any expert knowledge or cool code tricks, but... Ruby has a very awesome behavioral testing framework (RSpec), that's fluent and expressive. And since most of my time I work in C# (also some Java) that has your standard Unit Testing that's nowhere as awesome as the one that Ruby has, I decided that C# could use one.

Enter CSpec a behavioral, expressive and fluent testing framework for C# :-).

The main problem was that Ruby is a dynamic language and one of the most fluent and expressive so such framework is achievable but C# is static typed at heart and has some functional elements, it was obvious right away that CSpec would never be RSpec but my goal was to get as close as possible.

So in RSpec a sample code would look like:

# bowling_spec.rb
require 'bowling'

describe Bowling, "#score" do
  it "returns 0 for all gutter game" do
    bowling = Bowling.new
    20.times { bowling.hit(0) }
    bowling.score.should == 0
  end
end

Whereas the same code in CSpec looks like:

public class BowlingSpec: CSpecFacade<Bowling>
{
    public BowlingSpec()
     : base(new BowlingSpec())
    {
         //this describes the initial state of properties 
         //after initalization.
         Should(@have => ObjSpec.Score == 0);
    }

    //special delegate
    DescribeAll describe_bowling_score =
            (@it, @do) =>
            {
                @it("returns 0 for all gutter game");
                int game = 20;
                game.Times(()=>{ @do.hit(0) });
                @do.Should(@be => 0);
            };
}

There is just a little more code involved but it looks similar :-). To achieve the Should functionality I had to basically implement a parameter parser so when typing should it does actually matter what you write @be stands for equality test, but @have acts like a null check for ref types and truth check for bools.

To test the code either you need to get the instance of a test runner class and call it on the BowlingSpec or use the shell console and point it to the assembly, this will run tests and print all of the descriptions.

Now I could write on about how I did the framework and what's need to be done, but as I'm putting this thing to codeplex I'l just post the link here.

Feedback and Help is appreciated :-).

Bonus:

Apparently C# compiler has a bug in the parser as my framework pushes delegates and functional programming to it's limits ;-). I stumbled on it when I was trying to test CSpec in CSpec and in one case I had strange exceptions about the Action delegate that represents the @it tag.

private void CreateOperations()
        {
            run_on_type =
               (@it, @do) =>
               {
                   @it("Runs all of the operations contained in a type");
                   @do.RunTestOnType(myClassSpec.GetType());
                   @do.Passed.Should(@be => 3);
                   @do.Failed.Should(@be => 0);
               };
        }

The exception stated that: "Delegate Action does not take 1 arguments", but that's not true as IT takes one string argument :-), and converting the code to:

//MS aparently has a bug in the code.
//without this nothing will work and the DESCRIBE ALL delegate will throw exception.
//In mono it works perfect.
private Action<string> dummy;

private void CreateOperations()
        {
            run_on_type =
               (@it, @do) =>
               {
                   @it("Runs all of the operations contained in a type");
                   @do.RunTestOnType(myClassSpec.GetType());
                   @do.Passed.Should(@be => 3);
                   @do.Failed.Should(@be => 0);
               };
        }

Solved the problem for me, so from my point of view this looks like a bug.

Saturday, February 20, 2010

C# ICollection Extensions

C# ICollection Extensions:

One thing I love about the C# (3.5) are lambda expressions and what can be done to them, they provide a very flexible method of writing more functional code, take linq for e.g.

The ICollection interface provides a handful of extensions for more functional way of writing code which I use regularly in C# (especially in data access services), but it has some features missing that you would wish to have.

We could add a MappingObject as an Extension to ICollection, but I'm not going to do that here, instead we are going to add another missing feature that comes in handy in Testing, generating items for a collection based on a lambda function.

So let's see the implementation:
    /// <summary>
    /// ICollection Extensions
    /// </summary>
    public static class ICollectionExtensions
    {
        /// <summary>
        /// Generates items based on a given function.
        /// </summary>
        /// <param name="collection">collection.</param>
        /// <param name="length">length.</param>
        /// <param name="func">func.</param>
        /// <returns>List of System Collections Generic I Collection T.</returns>
        public static ICollection<T> Generate<T>
            (this ICollection<T> collection, int length, Func<int, T> func) 
            where T : class
        {
            for (int i = 0; i < length; i++)
            {
                collection.Add(func(i));
            }

            return collection;
        }

        /// <summary>
        /// Generates the Unique items based on a given function and equality comparer.
        /// </summary>
        /// <param name="collection">collection.</param>
        /// <param name="length">length.</param>
        /// <param name="func">func.</param>
        /// <param name="comparer">comparer.</param>
        /// <returns>List of System Collections Generic I Collection T.</returns>
        public static ICollection<T> GenerateUnique<T>
            (this ICollection<T> collection, int length, Func<int, T> func, IEqualityComparer<T> comparer)
            where T : class
        {
            T item = null;
            bool addItem = true;
            List<T> list = collection.ToList();

            for (int i = 0; i < length; i++)
            {
                addItem = true;
                item = func(i);

                if (collection.Count == 0)
                {
                    collection.Add(item);
                }
                else
                {
                    list.Add(item);

                    for (int n = 0; n < list.Count; n++)
                    {
                        if (comparer.Equals(item, list[n]))
                        {
                            addItem = false;
                            break;
                        }
                    }

                    if (addItem)
                    {
                        collection.Add(item);
                    }
                }
            }

            return collection;
        }
    }

Not very much to explain here, we have two basic functions, the first is quite obvious, it add an item to a collection that's a result of our lambda function with index parameter and with T result.

The second one is a bit more complicated code vise but the logic behind it is simple, add only unique items to the collection, based on a lambda function that don't satisfy the IEqualityComparrer.

In case you don't know IEqualityComparrer has just two methods that you need to implement:

- Equals
- GetHashCode

By implementing the first you can tell what conditions need to be satisfied for two objects to be considered equal, the second one is to have an unique hash code for a object.

Having those extensions we can write code in a more functional way like so:
        public class A
        {
            public int i;
            public string s;
            public string s2;
        }

        public class Comparer : IEqualityComparer<A>
        {
            public bool Equals(A x, A y)
            {
                return x.i == y.i;
            }

            public int GetHashCode(A obj)
            {
                return obj.ToString().ToLower().GetHashCode();
            }
        }

        List<A> testFirst = (List<A>)new List<A>().Generate(20, x => new A() { i = 1 + x, s = "a" });
        List<A> testSecond = (List<A>)new List<A>().Generate(10, x => new A() { i = 1 + x });
        testSecond.GenerateUnique(20, x => new A() { i = 2 }, new Comparer());

I must say that I like this kind of code writing style, it may not be appealing to all, but overall I'm glad that I have this feature, it can be a real time saver in some cases.

Friday, February 19, 2010

F# Discriminated Unions

F# Discriminated Unions:

While learning about the features of F# Discriminated Unions has to be one of the best features out there along with pattern matching and Language oriented features. The allow you to represent a complex data structure, that can be recursive, like trees for e.g.

Probably the most common Discriminated Union in F# would be an Option, where the type can have Some value of generic type or None.
type Option =
    | Some of 'a
    | None

What's great about them that then don't need to hold a value or a concrete type, can be composed of several other types, and contain members for some sorts of basic operations. Combine them with pattern matching and you can do all sorts of magic.

So let's build a Tree type in F#:

A tree can have a Leaf and a Node.

- Leaf can have a value.
- Node is composed of two other Tree types being a Node or Leaf
type Tree<'t> =
    | Leaf of 't
    | Node of Tree<'t> * Tree<'t>;

And that's it we can start writing trees, and analyzing them if needed, but let's add some members here also.
What we would need is the ability to print a tree in a readable format, and possibly generate one by passing the depth that we want.

Let's add those members to the Tree type.
member tree.Print = 
        let rec print n pad =
            match n with
            | Node(x,y) ->; printfn "%sNode" pad; print x (pad + " "); print y (pad + " ");  
            | Leaf(x) ->; printfn "%sLeaf %A" pad x;
        print tree ""

What's going on here?

We create a member that traverses the using pattern matching and prints the tree, the pad parameter is used to produce a nice view of the nesting of the elements.
member tree.Generate depth =
        let rec generate depth expr =
            match depth with
            | 0 -> expr; 
            | _ -> generate (depth - 1) (Node(expr, expr));
        generate depth tree

Again using pattern matching we create an expression that represents our tree, and using recursion we pass the expr to the node if the depth parameter is not equal zero.

So the whole code for this type looks like this:
type Tree<'t> =
    | Leaf of 't
    | Node of Tree<'t> * Tree<'t>
    member tree.Print = 
        let rec print n pad =
            match n with
            | Node(x,y) -> printfn "%sNode" pad; print x (pad + " "); 
            print y (pad + " ");  
            | Leaf(x) -> printfn "%sLeaf %A" pad x;
        print tree ""
    member tree.Generate depth =
        let rec generate depth expr =
            match depth with
            | 0 -> expr; 
            | _ -> generate (depth - 1) (Node(expr, expr));
        generate depth tree

Using just a few lines of  expressive code we created a whole tree structure with members.

Now let's test the tree:
let (t:Tree<int>) = Node(Leaf 1, Leaf 2)
let genTest = t.Generate(4)
let printTest = t.Print

printfn "%A" (genTest)
This was very brief introduction into F#  Discriminated Unions, as with this feature many thing's are possible like creating ASTs and using other F# features creating whole DSL languages, but what was covered here should come in handy to anyone interested in F# programming, and Tree structures.

Tuesday, February 16, 2010

F# Operators

F# Operators:

I've been studying F# and writing more and more code in it, and I'm intrigued by it's features. It has some very powerful and complex (to grasp) features but even combining the most simple features that language provides we can write code in very expressive way and also do some amazing things.

Let's look at F# operators:

In F# being a functional language everything is a function so operators are also functions, the interesting thing is that F# standard operators can be represented in different notations.

So for example the "+" operator can be represented as:

let x = 2 + 3         Infix Notation
let y = (+) 2 3      Postfix Notation

The nice thing about F# is that you can define your own operators that are both Infix and Postfix assignable
and being functions you can do all sorts of operations in them. Besides that F# functions can be curried that means their value can be accumulated and we can pass one parameter to the function.

Let's define our own operator that will measure time taken to execute our functions:

/// Measures time taken to execute a function
let (%%%) func p = 
    let time = new System.Diagnostics.Stopwatch();
    time.Start();
    let result = func p;
    time.Stop();
    time.ElapsedMilliseconds;

So what's happening here?

We just created a function that takes 2 parameters (we don't need to tell the compiler what types those are, he will manage to figure that out by itself) that takes our function and the parameters that will be passed to the function, next we create a Stopwatch (this should be familiar from C#, VB.NET perhaps) and start it and call our function with p, what's important here that even if you don't want the function result you need to assign it to something (let result) the compiler will assume that the function result will be a unit (void) and will not let you to measure functions that return something, but after adding the "let result" the compiler will assume that your func will return some generic type (a generic type can be a unit).

Now we can use this operator in Infix and Postfix notation but Postfix just seams better for this kind of operation.

//a function that returns int.
let sum (a, b, c) = a + b + c 
printfn "%A" ((%%%) sum (2,3,4))  

//a function that returns unit (void)
let display text = printfn "Display:::%s" text 
printfn "%A" ((%%%) display "Hello There")

If you are interrested how the code is looking in C# here it is:

[CompilationArgumentCounts(new int[] { 1, 1 })]
public static long op_PercentPercentPercent<a, b>
(FSharpFunc<a, b> func, a p)
{
    Stopwatch time = new Stopwatch();
    time.Start();
    b result = func.Invoke(p);
    time.Stop();
    return time.ElapsedMilliseconds;
}

So as you can see this is a standard function for the most part.

This was very brief introduction into F# operators and notations, if I will find time and ideas more will come in this topic, but probably in my next post I'm going to move on to something else regarding F# or C# (of course something great ;-) )

Friday, February 12, 2010

F# Learning & Tests

F# Performance:


I'm starting my adventure with F#. I've heard some good things about it, more so that it's target is more focused on scientific calculation, then a pure bl development, so probably it should be also faster (tail calls & new optimized Il instructions). There are some performance comparisons on F# and C# but I've decided to do my own, and get to know the language a bit (as I don't know it at all).

Notice. This post isn't about comparing performance of both C# and F# it's more what i found out learning the basics so this is by no means professional performance test (tail calls are on in F#).

So lets start with a simple fib function straight from a mathematical definition:
//F#
let rec fib(n) =
if n = 1 then 1
elif n = 2 then 2
else
fib(n - 1) + fib(n - 2)

//C#
public long Fib(int n)
{
if (n == 1)
return 1;
else if (n == 2)
return 2;
else
return Fib(n - 1) + Fib(n - 2);
}
rec in F# tells the function that it will use recurrence

This version is very similar to a C# version nothing really new about it.

Wen we run it the time to calculate the sequence for n = 42 we get:

F# handles it in around 7 sec.
C# handles it in around 9 sec.

So F# is a little bit faster here, when we decompile the code (im not going to show you that) it will be clear that the F# version is shorter.

Now let's use a different aproach F# has a nice match mechanism so lets use that and lets do a signle recrrence call to fib function insted of two:
//F#
let fibA(n) =
let rec fibx (n, a, b) =
match (n, a, b) with
| (0, a, b) -> a
| _ -> fibx (n - 1, a + b, a)
fibx (n, 0I, 1I)

//C#
public long FibA(int n)
{
return Fibx(n, 0, 1);
}

private long Fibx(int n, int a, int b)
{
if (n == 0) return a;
else return Fibx(n - 1, a + b, a);
}
the 'I' on fibx call are telling the compiler to use BigIntegers.

Still we can do the same in C# by replacing the match witch switch/case. (Match is a switch/case in IL)

Now if we run the code for n = 42 we get different results:

F# handles it in around 350 ms.
C# handles it in around 5 ms (wow).

But still this code is very similar to C# in structure, so let's try doing it the F# way all the way ;-)
let fibs = Seq.unfold (fun (a, b) -> Some(a, (b, a + b) )) (1,1)
let x = Seq.toList (Seq.take 42 fibs);
Now this at first can be hard to understand what's going on here, in short we build a sequence from a function that generates the data . The (1,1) are function parameters as in F# everything is a function.

So this is a 1 line implementation of the fib seqence (nice).

Again if we run the code for n = 42 we get:

F# handles it in around 300 ms.

So as far as my learning of F# goes and the performance testing for recurrence problem C# can handle it better if you cut the problem to a single recurrence call on the fib, but when applying the function from it's mathematical definition F# is faster, but I could be doing it all wrong with F# and thus the performance could be lowered.

Next on my list is writing some collection sorting in F# and learn about its data types as those could be potentially used with ADO.NET to get data in a very flexible way.

Tuesday, February 9, 2010

Some fun with Lambdas, MappingObject


Mapping Object:


This probably isn't the most original piece of code that can be done with Lambda expressions but I think it has some useful applications.

I love Lambda Expressions and anonymous methods and the things that one do with them, to accomplish his goals, to make code more dynamic, clean, and more flexible.

Sometimes when working with a data centric application that's plugged to ORM (or not) that you may deal with large objects where some or most properties are assigned from other objects according to some bl rules. Manually setting such rules in code is plain boring and requires a lot of work when you are just doing a brain dead job, and if it can't be done automatically via reflection, then this kind of job is meh. fortunately there are lambda expressions that make the whole thing a little more bearable.

Our goal here is to create a simple class that will behave like a object mapper, we still need to tell what maps to what but by using lambdas we will end up in more clean and flexible and shorter piece of code (and of course we will learn how to use lambdas ;) ).

So let's see the class diagram.
This class could have existed without the interfaces but I wanted to do a fluent kind of a class and have a base interface that other mapping interfaces could extend for different behavior, like for e.g have a collection of mapping states in a MappingObject that could re map itself based on the maps that were entered.

As you can see from the diagram we have two MappingObjects the first one just accepts a T source class and then applies the mapping from other classes. The second one accepts two classes T and N so it just maps one know class to another.

So let's look at the code:
    /// <summary>
/// Defines the base mapping contract.
/// </summary>
public interface IMap
{
void Map();
}

/// <summary>
/// Defines mapping operations when base object
/// is considered to be mapped with many others.
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IMap<T> : IMap
{
IMap<T> AddMapping<N>(Action<T, N> map, N obj)
where N : class;
IMap<T> AddMapping<K, N>
(Predicate<K> condition, Action<T, N> map, N obj, K cond)
where K : class
where N : class;
}

/// <summary>
/// Defines mapping operations of two objects.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="N"></typeparam>
public interface IMap<T,N> : IMap
{
IMap<T,N> AddMapping(Action<T, N> map);
IMap<T, N> AddMapping<K>
(Predicate<K> condition, Action<T, N> map, K cond)
where K : class;
}

/// <summary>
/// The Mapping object,
/// that defines how object fields are assigned.
/// </summary>
/// <typeparam name="T"></typeparam>
public sealed class MappingObject<T> : IMap<T> where T : class
{
List<KeyValuePair<Delegate, object>> mapping;
private T mapObj1;
private Delegate map;

/// <summary>
/// Initializes a new instance of the 
/// <see cref="MappingObject&lt;T, N&gt;"/> class.
/// </summary>
/// <param name="obj1">The obj1.</param>
public MappingObject(T obj1)
{
this.mapObj1 = obj1;
this.mapping = new List<KeyValuePair<Delegate, object>>();
}

/// <summary>
/// Adds the mapping.
/// </summary>
/// <typeparam name="N"></typeparam>
/// <param name="map">The map.</param>
/// <param name="obj">The obj.</param>
public IMap<T> AddMapping<N>(Action<T, N> map, N obj)
where N : class
{
this.mapping.Add(new KeyValuePair<Delegate, object>
(Delegate.CreateDelegate(map.GetType(), map.Method), obj));
return this;
}

/// <summary>
/// Adds the mapping if the condition is fulfilled.
/// </summary>
/// <typeparam name="K"></typeparam>
/// <param name="condition">The condition.</param>
/// <param name="map">The map.</param>
public IMap<T> AddMapping<K, N>
(Predicate<K> condition, Action<T, N> map, N obj, K cond)
where K : class
where N : class
{
if (condition(cond))
{
this.mapping.Add(new KeyValuePair<Delegate, object>
(Delegate.CreateDelegate(map.GetType(), map.Method), obj));
}
return this;
}

/// <summary>
/// Starts Mapping operation.
/// </summary>
public void Map()
{
foreach (var target in mapping)
{
this.map = Delegate.
CreateDelegate(target.Key.GetType(), target.Key.Method);
this.map.DynamicInvoke(mapObj1, target.Value);
}

}
}

/// <summary>
/// The Mapping object, 
/// that defines the field mappings between two objects.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="N"></typeparam>
public sealed class MappingObject<T, N> : IMap<T, N>
where T : class
where N : class
{
private T mapObj1;
private N mapObj2;
private Action<T, N> map;

/// <summary>
/// Initializes a new instance of the 
/// <see cref="MappingObject&lt;T, N&gt;"/> class.
/// </summary>
/// <param name="obj1">The obj1.</param>
/// <param name="obj2">The obj2.</param>
public MappingObject(T obj1, N obj2)
{
this.mapObj1 = obj1;
this.mapObj2 = obj2;
}

/// <summary>
/// Adds the mapping.
/// </summary>
/// <param name="map">The map.</param>
public IMap<T, N> AddMapping(Action<T, N> map)
{
this.map += map;
return this;
}

/// <summary>
/// Adds the mapping if the condition is fulfilled.
/// </summary>
/// <typeparam name="K"></typeparam>
/// <param name="condition">The condition.</param>
/// <param name="map">The map.</param>
public IMap<T, N> AddMapping<K>
(Predicate<K> condition, Action<T, N> map, K cond)
where K : class
{
if (condition(cond))
{
this.map += map;
}
return this;
}

/// <summary>
/// Starts Mapping operation.
/// </summary>
public void Map()
{
this.map(mapObj1, mapObj2);
}
}
The code is simple someone that never did any lambdas or generic may find it hard to understand at first but it should be very clear.

With this code insted of saying largeObjA.PropA = largeObjB.PropB; or
if(largeObjB.PropB) { largeObjA. PropA = something } x times.

we could write:
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
C c = new C();

c.z = "z";

a.i = 100;
a.s = "a";

b.x = "bx";
b.y = "1";

MappingObject<A> mo = new MappingObject<A>(a);
mo.AddMapping<C>((x, y) => x.s2 = y.z, c);
mo.AddMapping<C, B>(k => k.z == "z", (x, y) => x.s2 = y.x, b, c);
mo.Map();
}
}
classes A, B and C contain just some fields.

Now this is purely a cosmetic issue between normal assignment based on bl rules and lambdas but i prefer lambdas, and if we implement the mapping storage (via Hashtable for e.g) then things get interesting. We can store expressions and compile them later, or just delegates and store then and then load when needed, Maybe Ill expand this classes in another post and add the mapping storing features and some others as well.


 
ranktrackr.net