Friday, December 09, 2011

Little Schemer in Clojure

Recently I decided to brush up my completely rusted knowledge of Scheme. I was in the process of reviewing it when I came across Clojure and figured why not try to run these in parallel. Two birds with one stone - a JVM language if I needed to fall back into the warmth of Java and Scheme syntax to get away the boredom of Java's verbosity.

With that in mind, I will go through the Little Schemer book and attempt to do the exercises in Clojure.
So here is chapter 1 from the Little Schemer:

Concept Scheme Clojure
Define a list '(1 2 3) '(1 2 3)
Set list to a variable (define x '(1 2 3)) (def x '(1 2 3))
Get first item from list (car x) (first x); or
(define car [x] (first x))
Get second to last items from list (cdr x) (rest x); or
(define cdr [x] (rest x))
Are two lists equal? (eq? x y);
where (define y '(2 3))
(= x y);
where(define y '(2 3))
Add an atom to a list? (cons 0 x);
will return (0 1 2 3))
(cons 0 x);
will return (0 1 2 3)
Is this an atom? (atom? x) - returns #f;
where
(defun atom? (x)
(lambda (x)
(and (not (pair? x)) (not (null? x))))))
(atom? x) - returns #false;
where
(defn atom? [x]
(not (coll? x)))

I am using MIT-Scheme & Clojure 1.3 versions.
Setting up Scheme is easy, run MIT-Scheme.app on Mac, it brings up Edwin - the scheme emacs interpreter. Running commands requires C-x C-e on the REPL.

Clojure is easier do a java -cp /PATH/TO/clojure-1.3.0/clojure-1.3.0.jar clojure.main

- Harpreet

0 comments: