29 May 2013

Functional language for a java developer

Why should you learn it? IMHO, very important and underestimated argument is: it makes you a better programmer. What is more, you are probably already using it (javascript) and clojure and scala get more and more attention so it may be a good investment. But there is another, less obvious reason: it will help get a java job. A lot of interview questions are short algorithmic tasks. You can find one at almost every interview. Just pick the task, say that it would be easier to write it in a functional language and do it. Let's see a few examples. I asked google for 'programming interview questions' and I landed here. You can easily pick some tasks:

Create all permutations of a string. Here, haskell version is really impressive
permutation [] = [[]]
permutation xs = [x:ys | x <- nub (xs), ys <- permutation (delete x xs)]
In an array 1-100 numbers are stored, one number is missing how do you find it?
missing = succ . length . takeWhile id . zipWith (==) [1..] . sort
In an array 1-100 exactly one number is duplicate how do you find it?
duplicated = length . takeWhile id . zipWith (==) [1..] . sort
or after removing duplication:
increasingPrefixLength = length . takeWhile id . zipWith (==) [1..] . sort
missing = succ . increasingPrefixLength
duplicated = increasingPrefixLength
just for clarification, let's see how it works:
missing [1,3,2,5,6]
-- 4
duplicated [3,2,1,2,4]
-- 2
From other source: sum of digits of decimal expansion of 100!
(apply + (map #(Integer/parseInt (str %)) (str (apply *' (range 1 101)))))
number of zeros in decimal expansion of 100!
(count (filter #(= \0 %) (str (apply *' (range 1 101)))))
and the same in haskell (with currying and compact syntax for function composition)
sum . map digitToInt . show $ product [1..100]
length . filter (== '0') . show $ product [1..100]
Why functional style is useful? Often it's simpler because it has less edge cases (yes, you have to know the language and understand the FP). Of course above tasks aren't much more difficult in procedural approach and still, during the interview, you will probably have to solve them also in java. But I guarantee you: after such an answer you are a few points ahead of your competitors.

0 komentarze :

Post a Comment