Friday, 14 February 2014

Closure, Coroutine, Idempotent and Reentrancy

Closure - First class function that have access to free variables in a lexical environment
Coroutine - is a subroutine that have multiple entry points for suspending and resuming at certain locations - ex, C# we can use yield.
Idempotent - is an operation that be called multiple times without changing the result beyond initial application - ex, Cancel Order/Change address are idempotent, but Placing an order is not.
Reentrant - a re-entrant block of code is one that can be entered by another actor before an earlier invocation has finished, without affecting the path that the first actor would have taken through the code. That is, it is possible to re-enter the code while it's already running and still produce correct results.
Virtual Machine - Software emulation of a computer, two types - System VM and Process VM. Process VM provides portability and flexibility, and is bound to a single process. Loads when process load, and unloads when process goes out of scope. Process will be restricted to the resources/abstraction provided by VM. CLR is an example of Process VM

Thursday, 13 February 2014

C# Closure

As per wiki, Closure is a first class function with free variables that are bound in the lexical environment.

First class function is function that are treated as variable. C# we have delegates.
Free variables, are ones that are accessible to function which are not either passed as argument or defined locally.
Lexical environment means scope.

We call it closure because, first class function closes the variable it refers. In the example below, though myVar goes out of scope after first inc(), it is closed by the first class function(inc). It would print 7 & 9.

static void Main(string[] args)
{
    var inc = GetAFunc();
    Console.WriteLine(inc(5));
    Console.WriteLine(inc(6));
}
 
public static Func<int,int> GetAFunc()
{
    var myVar = 1;
    Func<int, int> inc = delegate(int var1)
                            {
                                myVar = myVar + 1;
                                return var1 + myVar;
                            };
    return inc;
}