This is a series of articles about the world, everything and parenthesis.
Featured Post
The behavior function
The behavior function is an idea that spawned during the last few days when I thought about how I would program an industrial robot (the ‘classic’ orange robot). Using behavior functions, robots can be programmed in a more functional way. … Continue reading
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.