Monday 15 December 2008

99 Problems in Lisp

Since the only way to get up to speed with a programming language is to actually use it, thought I'd work my way through 99 Problems in Lisp, only in Clojure.

Obviously, these are probably daft implementations, so any improvements welcome. Anyways, on with the problems. Instead of using recursion, I've tried to always go for recur since calling functions directly always runs the risk of running out of stack space. This actually "feels" surprisingly clean, no more repeating function names in bodies. Odd

P01 - Find the last item in a list

(defn last-in-list [x]
((fn [x last]
(if (nil? x)
(recur (rest x) (first x)))) x nil))

P02 - Find the last but one in a list

(defn last-but-one-in-list [x]
((fn [x last]
(if (nil? (rest (rest x)))
(recur (rest x) (first (rest x))))) x nil))

P03 - Find the K'th element of a list

(defn element-at [x n]
(if (= n 0)
(first x)
(recur (rest x) (dec n))))

P04 - Find the length of a list

(defn length [x]
((fn [x acc]
(if (nil? x)
(recur (rest x) (inc acc)))) x 0))

P05 - Reverse a list

(defn my-reverse [x]
((fn [list acc]
(if (nil? list)
(recur (rest list) (cons (first list) acc)))) x nil))


  1. Dumb question, but how can I get these running?

  2. If you want to get these running in Clojure then just fire up a REPL, paste the definitions in and away you go.

    The Getting Started page is really helpful. Get Java installed and follow the instructions there.

    I highly recommend Slime + Emacs (there's a guide setting it up here).

    Hope that helps!