Functional Programming and Quicksort
Just stumbled upon the Haskell page.
Looks like Functional Programming really has some points :
- In functional programs, most of the times, the specification is THE code . Take for eg, the quicksort example in Haskell :
qsort [] = []
qsort (x:xs) = qsort elts_lt_x ++ [x] ++ qsort elts_greq_x
where
elts_lt_x = [y | y <- xs, y < x]
elts_greq_x = [y | y <- xs, y >= x]
- You specify what you want and not how you want it to be done. In the above example, you are just specifying the property ( invariant ) that is to be obeyed at every step of the algorithm. In case of imperative programming languages, you have to "mentally execute the programs to be able to write programs".
- The most important feature of a functional programming language is that functions are treated as first class objects, in the sense you can define functions at runtime, compose functions just like you would assign values to variables , use them to construct expressions in imperative functions.
- One more thing to be noted is the polymorphic nature of the above program. The quicksort program above can be used to sort chars, ints, list of chars, list of list of chars and so on. In case of C, you would need separate programs for 1-D, 2-D and 3-D arrays.
- Other features of FPs include automatic garbage collection, lazy evaluation and so on.
- Pitfalls : The quicksort program is from the view of the specifier ( mathematician ? ). It has no references whatsoever to any code for memory management, so the Haskell system ends up using a lot of space behind the scenes, whereas in C, Hoare's method sorts the array in place.
- Functional Programming languages are more suited in those environments where users are willing to take a dip in performance while trading it with ease-of-program writing, fewer bugs and more often that not using programs which have been proven to be working correct !
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home