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
P01 - Find the last item in a list
P02 - Find the last but one in a list
P03 - Find the K'th element of a list
P04 - Find the length of a list
P05 - Reverse a list
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. OddP01 - Find the last item in a list
(defn last-in-list [x]
((fn [x last]
(if (nil? x)
last
(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)))
last
(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)
acc
(recur (rest x) (inc acc)))) x 0))
P05 - Reverse a list
(defn my-reverse [x]
((fn [list acc]
(if (nil? list)
acc
(recur (rest list) (cons (first list) acc)))) x nil))
Labels: clojure
Subscribe to Posts [Atom]