|Perl Monk, Perl Meditation|
Re: When would you use functional programming?by Dominus (Parson)
|on Oct 18, 2002 at 17:15 UTC||Need Help??|
As an aside, to illustrate the elegance of functional languages, consider the quicksort in Haskell.There's a very cool thing about this that you didn't mention. Sometimes in newsgroups or on this web site you see beginners do this:
when they want to find the minimum value in an array of numbers. And then other folks usually tell them that that is a bad move, because the sort takes O(n log n) time, but to scan the array looking for the minimum only takes O(n) time. This means that if you double the length of the array, the scan will take exactly twice as much time, but the sort will take more than twice as much time, and so no matter how fast your sorting is, for sufficiently large lists, the scan will be faster. Unfortunately, the array scan requires more code and isn't as transparently obvious.
The astonishing thing about the Haskell implementation is that you can write the analogous code:
and it will run in O(n) time. Sorting the whole list would require O(n log n) time, but Haskell figures out that it doesn't need to sort the entire list, and it manages to run the qsort function partially, just enough to sort the first element to the front. I find it incredible that this optimization just falls out naturally from Haskell's way of doing things.
This isn't a result of the fact that Haskell's a functional language, but rather that it's a lazy language. But it's difficult to imagine a usefully lazy language that wasn't also functional. The quest for useful laziness like this is one of the primary motivators for studying functional languages in the first place. A simpler example looks like this:
Here Perl, in spite of claiming the virtue of laziness, computes the value of the long complicated expression, but then throws it away and assigns zero to $x. The analogous code in Haskell never computes the value of the long complicated expression at all.
(Translation of the qsort for non-Haskell users:  is the empty list; [x] is a list that has just x and nothing else; ++ is the operator that appends two lists head-to-tail, and x:xs is the list you get by taking the list xs and appending x to the front. (So [x] and x: mean exactly the same thing.) gjb left a little bit of code off the end of the function, which I added back. [y | y <- xs, y > x] is something like Perl's map plus grep. It makes a list of all the y values from the list xs, subject to the constraint that y > x must be true. So [BLAH(y) | y <- xs, COND(y)] is very much like perl's map BLAH($_), grep COND($_), xs construction. Now you know Haskell. :) )