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]
    (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]
    (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. You also don’t need loop since recur will go to the function head:

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

    Note the double brackets.

Leave a Reply

Your email address will not be published. Required fields are marked *