In one of my computer science course, our professor start the class by asking a question: ‘what will you take with you if you get deserted in an FP world?’ some of us mentioned some popular FP languages, book,…he then took out a lambda symbol off his pocket….this is what you should take with you…it is the basis of functional programming language.
In lambda calculus, every expression is a function and its arguments and return values are also a function. And Each function only take a single argument(curried functions).
To multiply two numbers [ f(x,y)=x*y;] in its curried form :
f x y . x * y;
var double = f 2; //parameter ‘2′ is partially applied to the multiplication function.
double 5; //apply the second parameter to the partial function, this will give us 10.
functional programming language focuses on the ‘what’ instead of the ‘how’ of a problem.
lets write a function to get all prime factors of a number n.
first lets create helper functions to create list of integers b/n lo to hi and a filter function to filter a given list based on a given criteria.
//create a list of integers from lo to hi(in x::xs, x is the first element and xs is the rest of the list)
fun fromTo lo hi =
if lo > hi
then []
else lo :: fromTo (lo+1) hi;
//return a list where the elements pass test f
fun filter f null = []
| filter f x::xs =
if f x
then x :: filter f xs
else filter f xs;
//return true if n is is divisible by i
fun divides n i = (n mod i == 0);
fun factors n = filter (divides n) (fromTo 2 (n – 1));
How expressive is that?