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.