Front page

This is a series of articles about the world, everything and parenthesis.

Featured Post

Industrial robots in action

Recent Posts

Algorithm examples in clojure

The wikipedia page algorithm contains two simple examples of algorithms. Even though they are simple, the code examples really aren’t that beautiful. The first example is: find the largest number in a list.

=> (reduce (fn [x y] (if (> y x) y x)) [3 1 6 3 5 2])
6

The second example is calculating the largest common divisor with euclid’s algorithm. There is an “elegant” code example as follows:

5 REM Euclid's algorithm for greatest common divisor
6 PRINT "Type two integers greater than 0"
10 INPUT A,B
20 IF B=0 THEN GOTO 80
30 IF A > B THEN GOTO 60
40 LET B=B-A
50 GOTO 20
60 LET A=A-B
70 GOTO 20
80 PRINT A
90 END

Well… it is simple, and it is probably fast as well, but elegant?

=> (loop [a 3009 b 884] (if (zero? b) a (recur b (rem a b))))
17

=> (loop [a 40902 b 24140] (if (zero? b) a (recur b (rem a b))))
34

Success!!
Not only is this a lot more elegant (in my opinion), it also works when a = 0, where the “elegant” algorithm fails to end.

  1. Starting a process in clojure Leave a reply
  2. Recursive map Leave a reply
  3. List of all subsequences Leave a reply
  4. Numbers in clojure Leave a reply
  5. Using -> and ->> in clojure Leave a reply
  6. The core of a macro 1 Reply
  7. Fibonacci numbers and laziness Leave a reply