Friday, February 19, 2016

Why you should learn functional programming



The first time I came across functional programming is from wikipedia accidentally, for a quick sort example:

quicksort [] = []
quicksort (x:xs) = quicksort left ++ [x] ++ quicksort right
    where left = filter (<= x) xs
          right = filter (> x) xs


I was amazed (even today) by its simplicity, and come into the problem deeply without distracted by any kind of implementation details. before that I've spent quit sometime to understand quick sort, mainly by reading text book Introduction to Algorithms (It's a great book). However, it was the Haskell version helped me understand the algorithm deeply in mind.

Another example is finding /nth/ maximum element of an list, this is very similar to quicksort, except we can discard either left or right:

kth n (x:xs)
  | n <= len = kth n right
  | n == 1 + len = x
  | otherwise = kth (n - len - 1) left
    where left = filter (<= x) xs
          right = filter (> x) xs
          len = length right

Thus it requires less time complexity (average time complexity is O(n)). And I think it's more easier for understanding the problem.

No comments:

Post a Comment