Thursday, August 21, 2014

Functional Programming

There are two programming paradigms

Imperative programming: telling the "machine" how to do something, and as a result what you want to happen will happen.
Declarative programming: telling the "machine" what you would like to happen, and let the computer figure out how to do it.

FP : Creating abstractions using functions . Creating Higher Value Functions.

E.g to find prime numbers odd numbers, even numbers all encompass three logics
1) Iterating
2) apply the test ( is a prime, or an odd number, etc
3) Generating the result

Functional programming is all about abstracting ! and # to another function

private static IEnumerable<int> Find(this IEnumerable<int> values, Func<int, bool> test)

imperative syle
var numbers = [1,2,3,4,5]
var doubled = []

for(var i = 0; i < numbers.length; i++) {
  var newNumber = numbers[i] * 2
  doubled.push(newNumber)
}

//Declarative style
.//map creates a new array from an existing array, where each element in the new array is created by passing the elements of the original array into the function passed to map (function(n) { return n*2 } in this case).
var numbers = [1,2,3,4,5]
var doubled = numbers.map(function(n) {
  return n * 2
})

console.log(doubled)

Functional programming is all about Declarative programming
The base concept in functional programming is functions.
In functional programming we need to create functions as any other objects, manipulate them, pass them to other functions, etc.

Define Function types
Assign values to function objects (references)

=> Define Function Types
Func<double, double> f = Math.Sin;

We can use Action and predicate also for Funtion Types
Action<string> println = Console.WriteLine;
Predicate<string> isEmptyString = String.IsNullOrEmpty;

=> Define Function Values
Func<double, double> f1 = Math.Sin;
Func<double, double> f2 = Math.Exp;
double y = f1(4) + f2(5); //y=sin(3) + exp(5)
f2 = f1;
y = f2(9); //y=sin(9)


E.g.
        private static int Count<T>(T[] arr, Predicate<T> condition)
        {
            int counter = 0;
            for (int i = 0; i < arr.Length; i++)
                if (condition(arr[i]))
                    counter++;
            return counter;
        }

string[] words = new string[] { "one", "two", "three", "", "" };
            int numberOfEmptyBookTitles = Count(words, String.IsNullOrEmpty);

            int[] numbers = new int[] {-1, 2, 3, 6, 8, -15 , -4};
            int numberOfNegativeNumbers = Count(numbers, x => x < 0);

            Console.WriteLine("numberOfEmptyBookTitles" + numberOfEmptyBookTitles);
            Console.WriteLine(" numberOfNegativeNumbers " + numberOfNegativeNumbers);

Advantages of using Functional programming

1) Code Reuse: We can now reuse our utility functions which will result in a much smaller code base to achieve the same results.
2) Ease of Testing: Debugging and testing is easier because each function is not at the mercy of the state of some external object that we have to worry about replicating with our test.
3) Concurrency: If we stick strictly to a functional programming style and make sure there are no side-effects, our code is thread-safe by default because each thread will only be accessing objects instantiated within it's own thread stack and so there will be no objects having two threads trying to access them at the same time.

Converting "using" blocks to functions.
public static void Use<T>(this T item, Action<T> action) where T:IDisposable
{
    using (item)
    {
        action(item);
    }
}

// functional call using our utility method
new Disposable().Use(d =>
{
    // do something with d;
});

No comments:

Post a Comment