1 minute read

Sometimes I miss the named arguments feature in Python, for example: def slope(p1=(0,0), p2=(1,1)) return (float(p2[1] - p1[1])) / (p2[0] - p1[0]) => slope((1,2), (4,5)) => slope(p2=(2, 1)) The equivalent in clojure can be done using destructuring: (defn slope [& {:keys [p1 p2] :or {p1 [0 0] p2 [1 1]}}] (float (/ (- p2 1) (p1 1)) (- p2 0) (p1 0))) => (slope :p1 [1 2] :p2 [3 4]) => (slope :p2 [3 4]) => (slope)

1 minute read

Code kata

Problem Here is a list of students' exam scores. Write a function to sort them based on given criteria. Like Math first, then Physics and then chemistry and then English. (def exam-scores [{:math 78 :physics 80 :english 97 :chemistry 65} {:math 78 :physics 80 :english 66 :chemistry 65} {:math 78 :physics 54 :english 97 :chemistry 65} {:math 78 :physics 80 :english 97 :chemistry 61} {:math 100 :physics 89 :english 47 :chemistry 85} {:math 98 :physics 80 :english 79 :chemistry 65}]) Solution (defn rank [scores & criteria] (reverse (sort-by (fn [score] (mapv score criteria)) scores))) Note The sort-by in Clojure is very powerful, the idea is to reduce each row into one value that we know how to sort, like numbers, strings or lists.

1 minute read

Code kata

Problem Write a function steps, that takes a sequence and makes a deeply nested structure from it: (steps [1 2 3 4]) ;=> [1 [2 [3 [4 []]]]] Solution 1 (defn steps [s] (if (seq s) [(first s) (steps (rest s))] [])) Solution 2 Lazy version: (defn lz-steps [s] (lazy-seq (if (seq s) [(first s) (lz-steps (rest s))] []))) Note To see the difference, call the function like this:

1 minute read

Code kata

Problem Suppose a binary tree structure looks like this: {:val value :L <left-node> :R <right-node>} Write a function to balance insert node into the tree. Solution (defn insert [tree x] (cond (nil? tree) {:val x :L nil :R nil} (< x (:val tree)) (assoc tree :L (insert (:L tree) x)) :else (assoc tree :R (insert (:R tree) x)))) Note Here is the function to traverse the tree: (defn traverse [tree] (when tree (concat (traverse (:L tree)) [(:val tree)] (traverse (:R tree))))) Here is a helper function to create a tree.