On Triangles

In SICP 1.2.2 Tree Recursion we have Exercise 1.12 which asks us to code up a recursive solution to compute the elements of Pascals Triangle. 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Pascals Triangle has two rules - the numbers on the edge are 1 and the numbers inside the triangle is the sum of the two numbers in the previous row. A recursive solution is fairly simple : (in Clojure) (defn triangle [col row] (if (or (= col 0) (= col row)) 1 (+ (triangle (dec col) (dec row)) (triangle col (dec row))))) If the column is the first or the last one return 0 otherwise recurse up to get the two values in the prior row. »

Cond and friends

There are a number of different cond’s in Clojure. cond The classic cond. This replaces the standard if...else if....else that you find in other languages. It takes a set of test and expression pairs. For the first test that evaluates to true it will evaluate and return its corresponing expression. (cond (is-banana? me) "I am a banana" (is-slug? me) "I am a slug" :else "I am a turnip") => "I am a slug" cond-> Now cond short circuits - it will stop at the first true expression. »