Haskell functional programming

Did you ever hear something about functional programming? I'm sure you did, and if you didn't you should check it out. In one sentence it is basically a more mathematical approach to programming...but extremely efficient.
Consider for instance the following lines of code:

f[] = []
f(x:xs) = f ys ++ [x] ++ f zs
where
ys = [a | a <- xs, a <= x]
zs = [b | b <- xs, b > x]

Did you understand what it does?? It's the quicksort algorithm, expressed in just 5 lines. Initially it may look quite strange, but actually it is very intuitive. For instance in the first line f[] = [] is the definition of the recursive "basic" condition, what follows is the recursive call itself. The function accepts a list (x:xs), an x followed by many xs :) . The part f ys ++ [x] ++ f zs basically says that you take the "x" in the middle and you add ys before and zs after. Note this are the recursive calls on the function f. ys and zs are defined below, where ys is a list with elements "a" which will take values from the xs if a <= x. Essentially in ys all elements will be added which are before (less than) x. The contrary holds for the zs. And so you get the sorted list.

*Main> f [2, 4, 11, 4, 2, 18,5, 3]
[2,2,3,4,4,5,11,18]

Functional programming is extremely efficient. There exist a bunch of libraries which are written in functional programming languages. Even Microsoft added functional programming style pieces into C#, the C# lambda expressions which are very handy especially for dealing with lists (sorting, filtering etc...).

Resources:
Haskell in 10 minutes
Kindle

Comments

0

Your ad here?