99 Clojure Problems (1-4)

I’ve been learning new languages lately, and I’ve been using the 99 scala problems to help me learn important features of the languages.

I’m going to blog about my experiences with clojure.

Once I got through the hoops of starting with clojure (just download the eclipse plugin and go!), it was smooth sailing for the first four problems.

```(ns s99)
;; P01 (*) Find the last element of a list.
; Basically, this replicates the (last n) functionality already in clojure
(defn s99_last [input]
(loop [i input]
(let [a (first i)
b (first (rest i))]
(if (= b nil) a (recur (rest i))))))

; P02 (*) Find the last but one element of a list.
(defn penultimate [input]
(loop [i input]
(let [a (first i)
b (first (rest i))
c (first (rest (rest i)))]
(if (nil? c) a (recur (rest i))))))

; P03 (*) Find the Kth element of a list.
; By convention, the first element in the list is element 0.
; in clojure, nth already exists (nth n l)
(defn s99_nth [n input]
(loop
(if (= c n) (first i) (recur (inc c) (rest i)))))

; P04 (*) Find the number of elements of a list.
; This is the same functionality as clojure's (count l) function
(defn length [input]
(loop
(if (nil? (first i)) c (recur (inc c) (rest i)))))
```

So far, the lack of pattern matching makes things a little more difficult than scala or f#, but once I got a hang of the sea of parenthesis, it was easy to remember my college work with xquery.

7 Replies to “99 Clojure Problems (1-4)”

1. Clojure does support some pattern matching. For example the last function could be rewritten as

(defn s99_last [xs] (loop [[x & xs] xs] (if (= xs nil) x (recur xs))))

2. “last” being “s99_last”, not the “length” function..

3. Oh, wow!

Imagine a huge click as another piece falls into place. This comment definitely opened a huge door of understanding for me.

4. Glad I could help!

5. You also don’t need loop since recur will go to the function head:

```(defn penultimate [[x _ &amp; more]]
(if more (recur (next more)) x))```

Note the double brackets.

6. To be clear, using recur in the above manner is not stack consuming recursion, but acts just like loop.

7. ```(defn penultimate [ls]
(last (butlast ls)))```

Not as clever as the other solutions … but shorter.