Quantcast
Channel: Curiouser and Curiouser! on functional-programming
Viewing all articles
Browse latest Browse all 7

Across a vast Clojure gulf

$
0
0

Having conquered the Clojure Koans I'm doing some of the 4clojure problems to help me improve my Clojure skills.

One of the interesting things about 4clojure is that you can "follow" other users and, once you have solved a problem, you get to see their solutions. The advice is to follow some of the experts so that you can see what a real Clojure solution looks like.

It's both instructive and depressing to do so. By contrast with some of the solutions from people who've done all 155 of the 4clojure problems mine are are verbose, inelegant, and betray my ignorance of much of the deep power of Clojure's abstractions.

Here's an example:

"Write a function which returns the first X fibonacci numbers."

(= (__ 3) '(1 1 2))

(= (__ 6) '(1 1 2 3 5 8))

(= (__ 8) '(1 1 2 3 5 8 13 21))

Here's my solution to the problem:

(fn [n]
  (map (fn fib [n]
     (loop [n n]
       (condp = n
         0 1
         1 1
         (+ (fib (- n 1)) (fib (- n 2))))))
   (range n)))

To be fair to me, it works. But it's long-winded and doing far too much work. Let's take a look at what a more experienced Clojure programmer might come up with. How about:

#(take % (map first (iterate (fn [[a b]] [b (+ a b)]) [1 1])))

or

#(take % ((fn fib [a b] (cons a (lazy-seq (fib b (+ a b))))) 1 1))

The key difference is the use of a lazy sequence (via either lazy-seq or iterate) that generates an infinite expansion of the Fibonacci series. Then it's enough to just take as much of the sequence as required.

It's enough that this approach didn't occur to me, although I did try to think about better ways of generating the sequence (even thinking about iterate but not being able to see how I could apply it). The elegance with which my mentors generate their sequences is pretty inspiring.

I'm not beating myself up too much. Some of these guys may have prior functional experience or have been using Clojure for years. But it does rather highlight the gulf I still have to cross to master this language, not to mention paradigm, I have chosen.


Viewing all articles
Browse latest Browse all 7

Trending Articles