Wednesday, April 15, 2009

Wednesday, April 8, 2009

Learning LINQ

I came across the blog of Eric White and this is the best material to learn linq i have seen.

http://blogs.msdn.com/ericwhite/pages/FP-Tutorial.aspx

Talks about functional programming and who C# implements functional programming using Linq.

Here one more link for learning LINQ technology.
http://www.linqhelp.com/

Monday, April 6, 2009

Unity 1.2

Some thing to really look at new functionalities like Circular references with dependency injection, Interception with Unity http://unity.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=18855

Friday, April 3, 2009

MapReduce in F#

I came across the following link on MapReduce implementation in F#

http://www.twine.com/item/1229c60s4-4q/exploring-mapreduce-with-f

Also Microsoft is working on C# implementation known as LINQ to DataCenter.

For those who don't know MapReduce should think twice as anyone using google search is the user of MapReduce algorithm.

Wikipedia has clear explanation of the MapReduce http://en.wikipedia.org/wiki/MapReduce

WPF ConverterParameter

Just came to my knowledge and want share with people.

<TextBlock Text="{Binding Path=ABCD, Converter={StaticResource FormatConv}, ConverterParameter='{0:C}'}" />

The above code wont work i know there is nothing wrong in there but still compiler would cry about it.

One needs to add blank space in the ConverterParameter value and that will solve the problem.

ConverterParameter=' {0:C}'

Functional Fibonnaci series in C#

C# code for functional fibonnaci numbers

Func<int, int> fib = null;
fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;

Okay so you guys would think why would i declare the delegate in one line and instantiate in the next. The reason is that if you do everything in same line complier wont recognize the recursive call using the delegate. Try this

Func<int, int> fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;

Above code wont compile

Haskell code for same
fib n
| n == 0 = 0
| n == 1 = 1
| n > 1 = fib (n-1) + fib (n-2)

Wednesday, April 1, 2009

New Class in .Net 4.1

Came across a new class in framework .Net 4.1 StringOr<TOther>

public class StringOr<TOther> {
public StringOr(string stringValue, TOther otherValue);

public string StringValue { get; }
public TOther OtherValue { get; }
}

There are lot of situations where you store datetime and other values in string simply because they are not formatted correctly or there are chances that database may or may not return a value which can be converted to exact format.

StringOr<int> userInput= GetUserInput("Quantity");
string szUserInput=userInput.StringValue;
int intUserInput=userInput.OtherValue;

Here is the solution to that problem.

Monday, March 16, 2009

C# functional programming

So i finally decided to write on how we can achieve  funcational programming in C#.

Lets start with defining a function 

Math: f(x) = x
C#: Action<int> f = x =>x;

Math : f(x) =  6x + 2
C#: Func<int,int> f = x=> 6*x + 2;

Math: f(x,y) = 2x+ 3y
C#: Func<int,int,int> f = (x,y) => 2*x + 3*y;

function which returns a function
Func<int,Func<int,int>> fg = x => (y => y + x);

Friday, March 6, 2009

Monads Part 3

In functional programming, a monad is a kind of abstract data type used to represent computations (instead of data in the domain model). Programs written in functional style can make use of monads to structure procedures that include sequenced operations,[1][2] or to define arbitrary control flows (like handling concurrency, continuations, or exceptions).

Formally, a monad is constructed by defining two operations bind and return and a type constructor M that must fulfill several properties. These properties make possible the correct composition of functions that use values from the monad as their arguments (so called monadic functions). The monad acts as a framework in that it's a reusable behavior that decides the order in which the specific monadic functions are called, and manages all the undercover work required by the computation.[3]

The primary uses of monads in functional programming are to express input/output (I/O) operations and changes in state without using language features that introduce side effects[4]. Although a function cannot directly cause a side effect, it can construct a value describing a desired side effect that the caller should apply at a convenient time. However, I/O and state management are by no means the only uses of monads. They are useful in any situation where the programmer wants to carry out a purely functional computation while a related computation is carried out "on the side." In imperative programming the side effects are embedded in the semantics of the programming language; with monads, they are made explicit in the monad definition.

The name monad derives from category theory, a branch of mathematics that describes patterns applicable to many mathematical fields. (As a minor terminological mismatch, the term "monad" in functional programming contexts is usually used with a meaning corresponding to that of the term "strong monad" in category theory, a specific kind of category theoretical monad.[citation needed])

The Haskell programming language is a functional language that makes heavy use of monads, and includes syntactic sugar to make monadic composition more convenient. All of the code samples below are written in Haskell unless noted otherwise.

Definition


A monad is a construction that, given an underlying type system, embeds a corresponding type system (called the monadic type system) into it (that is, each monadic type acts as the underlying type). This monadic type system preserves all significant aspects of the underlying type system, while adding features particular to the monad.

The usual formulation of a monad for programming is known as a Kleisli triple, and has the following components:

1. A type construction that defines, for every underlying type, how to obtain a corresponding monadic type. In Haskell's notation, the name of the monad represents the type constructor. If M is the name of the monad and t is a data type, then "M t" is the corresponding type in the monad.
2. A unit function that maps a value in an underlying type to a value in the corresponding monadic type. The result is the "simplest" value in the corresponding type that completely preserves the original value (simplicity being understood appropriately to the monad). In Haskell, this function is called return due to the way it is used in the do-notation described later. The unit function has the polymorphic type t→M t.
3. A binding operation of polymorphic type (M t)→(t→M u)→(M u), which Haskell represents by the infix operator >>=. Its first argument is a value in a monadic type, its second argument is a function that maps from the underlying type of the first argument to another monadic type, and its result is in that other monadic type. The binding operation can be understood as having four stages:
a. The monad-related structure on the first argument is "pierced" to expose any number of values in the underlying type t.
b. The given function is applied to all of those values to obtain values of type (M u).
c. The monad-related structure on those values is also pierced, exposing values of type u.
d. Finally, the monad-related structure is reassembled over all of the results, giving a single value of type (M u).

In Object-oriented programming terms, the type construction would correspond to the declaration of the monadic type, the unit function takes the role of a constructor method, and the binding operation contains the logic necessary to execute its registered callbacks (the monadic functions).

In practical terms, a monad, unlike your everyday function result, stores function results and side-effect representations. This allows side effects to be propagated through the return values of functions without breaking the pure functional model. For example, Haskell's Maybe monad can have either a normal return value, or Nothing. Similarly, error monads (such as Either e, for some type e representing error information) can have a normal return value or an error value.

Moniod Part 2

A monoid is a set M with binary operation * : M × M → M, obeying the following axioms:
• Associativity: for all a, b, c in M, (a*b)*c = a*(b*c)
• Identity element: there exists an element e in M, such that for all a in M, a*e = e*a = a.
One often sees the additional axiom
• Closure: for all a, b in M, a*b is in M
though, strictly speaking, this axiom is implied by the notion of a binary operation.
Alternatively, a monoid is a semigroup with an identity element; it can also be understood as a category with closure.
A monoid satisfies all the axioms of a group with the exception of having inverses. A monoid with inverses is a group.
By abuse of notation we sometimes refer to M itself as a monoid, implying the presence of identity and operation. A monoid can be denoted by the tuple (M, *) if the operation needs to be made explicit.

Generators and submonoids
A submonoid of a monoid M is a subset N of M containing the unit element, and such that, if x,y∈N then x*y∈N. It is then clear that N is itself a monoid, under the binary operation induced by that of M. Equivalently, a submonoid is a subset N such that N=N∗, where the superscript * is the Kleene star. For any subset N of M, the monoid N* is the smallest monoid that contains N.
A subset N is said to be a generator of M if and only if M=N*. If N is finite, then M is said to be finitely generated.

Commutative monoid
A monoid whose operation is commutative is called a commutative monoid (or, less commonly, an abelian monoid). Commutative monoids are often written additively. Any commutative monoid is endowed with its algebraic preordering ≤, defined by x ≤ y if and only if there exists z such that x + z = y. An order-unit of a commutative monoid M is an element u of M such that for any element x of M, there exists a positive integer n such that x ≤ nu. This is often used in case M is the positive cone of a partially ordered abelian group G, in which case we say that u is an order-unit of G. There is an algebraic construction that will take any commutative monoid, and turn it into a full-fledged abelian group; this construction is known as the Grothendieck group.

Partially commutative monoid
A monoid for which the operation is commutative for some, but not all elements is a trace monoid; trace monoids commonly occur in the theory of concurrent computation.

Examples
• Every singleton set {x} gives rise to a one-element (trivial) monoid. For fixed x this monoid is unique, since the monoid axioms require that x*x = x in this case.
• Every group is a monoid and every abelian group a commutative monoid.
• Every bounded semilattice is an idempotent commutative monoid.
• Any semigroup S may be turned into a monoid simply by adjoining an element e not in S and defining e*e = e and e*s = s = s*e for all s ∈ S.
• The natural numbers, N, form a commutative monoid under addition (identity element zero), or multiplication (identity element one). A submonoid of N under addition is called a numerical monoid.
• The elements of any unital ring, with addition or multiplication as the operation.
o The integers, rational numbers, real numbers or complex numbers, with addition or multiplication as operation.
o The set of all n by n matrices over a given ring, with matrix addition or matrix multiplication as the operation.
• The set of all finite strings over some fixed alphabet Σ forms a monoid with string concatenation as the operation. The empty string serves as the identity element. This monoid is denoted Σ∗ and is called the free monoid over Σ.
• Fix a monoid M, and consider its power set P(M) consisting of all subsets of M. A binary operation for such subsets can be defined by S * T = {s * t : s in S and t in T}. This turns P(M) into a monoid with identity element {e}. In the same way the power set of a group G is a monoid under the product of group subsets.
• Let S be a set. The set of all functions S → S forms a monoid under function composition. The identity is just the identity function. If S is finite with n elements, the monoid of functions on S is finite with nn elements.
• Generalizing the previous example, let C be a category and X an object in C. The set of all endomorphisms of X, denoted EndC(X), forms a monoid under composition of morphisms. For more on the relationship between category theory and monoids see below.
• The set of homeomorphism classes of compact surfaces with the connected sum. Its unit element is the class of the ordinary 2-sphere. Furthermore, if a denotes the class of the torus, and b denotes the class of the projective plane, then every element c of the monoid has a unique expression the form c=na+mb where n is the integer ≥ 0 and m=0,1, or 2. We have 3b=a+b.
• Let < f > be a cyclic monoid of order n, that is, < f > = {f0,f1,..,fn − 1}. Then fn = fk for some . In fact, each such k gives a distinct monoid of order n, and every cyclic monoid is isomorphic to one of these.

Thursday, March 5, 2009

Lambda Calculus Part 1

In mathematical logic and computer science, lambda calculus, also written as λ-Calculus, is a formal system designed to investigate function defination, functiona application and recursion. Is is a useful tool in the investigation of problems in computability or recursion theory, anf forms the basis of a paradigm of computer programming called functional programming.

The key concept of lambda calculus is that of a lambda expression - a reification of the concept of a procedure without side effects. The lambda calculus can be thought of as an idealized, minimalistic programming language. It is capable of expressing any algorithm, and it is this fact that makes the model of functional programming an important one. Functional programs are stateless and deal exclusively with functions that accept and return data (including other functions), but they produce no side effects in 'state' and thus make no alterations to incoming data. Modern functional languages, building on the lambda calculus, include Erlang, Haskell,Lisp, ML, and Scheme, as well as more recent languages like F#, Nemerle, and Scala.

The lambda calculus derives its usefulness from having a sparse syntax and
a simple semantics, and yet it retains sufficient power to represent all computable
functions. Lambda expressions come in four varieties:
  1. Variables, which are usually taken to be any lowercase letters.
  2. Predefined constants, which act as values and operations are allowed in an impure or applied lambda calculus .
  3. Function applications (combinations).
  4. Lambda abstractions (function definitions).
The simplicity of lambda calculus syntax is apparent from a BNF specification
of its concrete syntax:
<expression> ::= <variable> ; lowercase identifiers
| <constant>  ; predefined objects
| ( <expression> <expression> ) ; combinations
| ( λ <variable> . <expression> ) ; abstractions.

Friday, February 27, 2009

Functional programming.

Recently i got taste of functinoal programming F# and was really zapped with what it can do. Any one who wants to learn about functional programming should start with following topics.

  1. Lambda Calculus
  2. Moniod f : a -> a
  3. Monads f: a ->Ma where M is side effect
Also first three topics would be helpful for people who want to use LINQ extensively in C#. All the LINQ expression are basically Monads.

Will be writing more about the functional programming in future post.

Monday, January 5, 2009

Monte Carlo Simulation for Dummies

History: The idea behind Monte-Carlo simulations gained its name and its first major use in 1944, in the research work to develop the first atomic bomb. The scientists working on the Manhattan Project had intractably difficult equations to solve in order to calculate the probability with which a neutron from one fissioning Uranium atom would cause another to fission. The equations were complicated because they had to mirror the complicated geometry of the actual bomb, and the answer had to be right because, if the first test failed, it would be months before there was enough Uranium for another attempt.

They solved the problem with the realization that they could follow the trajectories of individual neutrons, one at a time, using teams of humans implementing the calculation with mechanical calculators. At each step, they could compute the probabilities that a neutron was absorbed, that it escaped from the bomb, or it started another fission reaction. They would pick random numbers, and, with the appropriate probabilities at each step, stop their simulated neutron or start new chains from the fission reaction.

The brilliant insight was that the simulated trajectories would have identical statistical properties to the real neutron trajectories, so that you could compute reliable answers for the important question, which was the probability that a neutron would cause another fission reaction. All you had to do was simulate enough trajectories.

 

I know for most of people that went above there heads. So lets try to look it in a simple way.

Monte Carlo algorithm to compute the value of tex2html_wrap_inline68478from a sequence of random numbers. Consider a square positioned in the x-y plane with its bottom left corner at the origin as shown in Figure. The area of the square is r2, where r is the length of its sides. A quarter circle is inscribed within the square. Its radius is r and its center is at the origin of x-y plane. The area of the quarter circle is π*r2/4.

  
Figure: Illustration of a Monte Carlo method for computing π.

Suppose we select a large number of points at random inside the square. Some fraction of these points will also lie inside the quarter circle. If the selected points are uniformly distributed, we expect the fraction of points in the quarter circle to be

f = (πr2/4) / r2 = π/4

Therefore by measuring f, we can compute π. Program shows how this can be done.

class Program

    {

        static void Main(string[] args)

        {

            int trials = 10000000;

            Console.WriteLine("The value generated after number of {0} trials is {1}",trials, Pi(trials));

            Console.ReadLine();

        }

 

        public static double Pi(int trials)

        {

            Random rnd = new Random();

            int hits = 0;

            for (int i = 0; i <>

            {

                double x = rnd.NextDouble();

                double y = rnd.NextDouble();

                if (x * x + y * y <>

                    ++hits;

            }

            return 4.0 * hits / trials;

        }

    }

Program: Monte Carlo program to compute π.

The Pi method uses the Random.NextDouble() defined to generate (x,y) pairs uniformly distributed on the unit square (r=1). Each point is tested to see if it falls inside the quarter circle. A given point is inside the circle when its distance from the origin, Root(x2+y2) is less than r. In this case since r=1, we simply test whether x2 + y2 <>

How well does Program work? When 1000 trials are conducted, 792 points are found to lie inside the circle. This gives the value of 3.168 for π, which is only 0.8% too large. When 108 trials are conducted, 78535956 points are found to lie inside the circle. In this case, we get π = 3.14143824 which is within 0.005% of the correct value!