JavaRanch Home    
 
This page:         last edited 20 January 2014         What's Changed?         Edit

Learn Clojure   

Clojure is -like Scala- a functional dialect of Java, but its basic syntax is closer to Scheme. You can get it at http://clojure.org/. Once you have extracted the jar file, start the interpreter with

java -cp clojure.jar clojure.main

and you're ready to evaluate stuff:

user==> (+ 1 2 3)
6

Code that's saved in files can be loaded by something like

(load-file "Euler1.clj")

Clojure question can be asked in the Incubator > Clojure forum here at JavaRanch, and there are more interesting links at BeClojurian.


An example

To start with, here's a short Clojure program that solves the first problem of Project Euler : If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

(defn divisible-by-3-or-5 [n]
	(or 
		(= 0 (rem n 3))
		(= 0 (rem n 5))))

(defn euler1-minus1 [n]
	(cond 
		(< n 2)
			0
		(divisible-by-3-or-5 n)
			(+ n (euler1-minus1 (dec n)))
		:else
			(euler1-minus1 (dec n))))

(defn euler1 [limit]
	(euler1-minus1 (dec limit)))

Here's a more idiomatic solution that uses higher-order functions - reduce and filter:

(defn euler1-ho [limit]
	(reduce + (filter divisible-by-3-or-5 (range limit))))


More examples

Clojure is particularly well suited for problems that are defined recursively, or that can solved by recursive algorithms. Here are functions that calculate the factorial of a number (n!) and the numbers of the Fibonacci sequence.

(defn factorial [n]
    (if (= n 0)
        1
        (* n (factorial (- n 1)))))

(defn fibonacci [n]
    (cond
        (= n 0) 0
        (= n 1) 1
        true    (+ (fibonacci (- n 1)) (fibonacci (- n 2)))))
This recursive "fibonacci" code is considered a "natural" implementation as it mirrors the mathematical definition of the function very closely. However this recursive version is very inefficient, and will become slow very quickly for growing n. Consequently it is not unusual in functional languages to replace inefficient recursive functions with equivalent tail recursive versions. Clojure has ways of dealing with that, though: http://en.wikibooks.org/wiki/Clojure_Programming/Examples/Lazy_Fibonacci

CategoryLearnSomethingNew

JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton