Why you should care about functional programming

Preview:

DESCRIPTION

A introductory talk about the benefits of functional programming

Citation preview

Why you should care about Functional Programming

Dhananjay Nene

TechWeekend 5December 18th, 2010

What is functional programming about ?

Functions = input + transformation + output

def add(x,y) : return x + y

def double(x) : return 2 * x

NO side effects

Unit Testing or Integration Testingwhen NO side effects ?

Benefit 1 : Testability

Benefit 2 : Easier Integration

All variables are final and are an alias to the result of a computation

A variable thus cannot have a different value at different points in time

Benefit 3 : Concurrency (no locking)

Constructs to easily parallelise operations

Benefit 4 : Ability to leverage multicores (if applicable)

Higher Order Functions :Functions which take functions as parameters

def repeat(f,x) : return f(x,x)

double(x)

OR

repeat(add,x)

I like to imagine HOFs as policy injection

Brevity

public static <E extends Comparable<? super E>> List<E> quickSort(List<E> arr) { if (arr.size() <= 1) return arr; E pivot = arr.getFirst(); //This pivot can change to get faster results List<E> less = new LinkedList<E>(); List<E> pivotList = new LinkedList<E>(); List<E> more = new LinkedList<E>(); // Partition for (E i: arr) { if (i.compareTo(pivot) < 0) less.add(i); else if (i.compareTo(pivot) > 0) more.add(i); else pivotList.add(i); } // Recursively sort sublists less = quickSort(less); more = quickSort(more); // Concatenate results less.addAll(pivotList); less.addAll(more); return less;}

qsort1 :: Ord a => [a] -> [a]qsort1 [] = []qsort1 (p:xs) = qsort1 lesser ++ [p] ++ qsort1 greater where lesser = filter (< p) xs greater = filter (>= p) xs

Think different :

Recursion or Comprehensions instead of Loops

Pattern Matching instead of if conditions

Pattern Matching instead of State Machines

Information Transformation instead of sequence of tasks

Persistent Data Structures

Powerful concurrency constructs : Actors

Software Transactional Memory

At what cost ?

Retraining the brain: Fixed Cost

(Remember OO?)

Actual development costs (variable) likelyto be lesser.

Could not find specific case studies.

Why ?

Programs are often smaller

Have a cleaner expression of intent(what instead of how)

Big ball of mud is harder to achieve with pure functions

Better future proofing in terms of beingable to leverage multicore

Once you are able to read code written in functional style, its a lot more enjoyable

Faster, better, (cheaper?) and Enjoyable!

Recommended