August 29, 2018
Live Clojure Cheat Sheet: Branching Functions
We're continuing our interactive cheat sheet with Clojure's branching functions. The idea here is to provide basically a single example using each function, eschewing any explanations or attempt at being exhaustive. For a more comprehensive guide, use ClojureDocs.
(defn is-small? [number]
(if (< number 100) "yes" "no"))
(is-small? 50)
(is-small? 500)
(defn has-neg [coll]
(if-not (empty? coll) ;; = (if (not (empty? coll)) ...
(or (neg? (first coll)) (recur (rest coll)))))
(has-neg [])
(has-neg [1 2 -3 4])
(when (= 1 1) true)
(when (not= 1 1) true)
(map
#(when-not (= %2 %3) [%1 %2 %3])
(iterate inc 0) ; a lazy list of indecies
[:a :b :c]
[:a :a :a])
(defn drop-one
[coll]
(when-let [s (seq coll)]
(rest s)))
(drop-one [1 2 3])
(drop-one [])
(when-first [a [1 2 3]] a)
(when-first [a []] :x)
(when-first [a nil] :x)
(defn sum-even-numbers [nums]
(if-let [nums (seq (filter even? nums))]
(reduce + nums)
"No even numbers found."))
(sum-even-numbers [1 3 5 7 9])
(sum-even-numbers [1 3 5 7 9 10 12])
(defn pos-neg-or-zero
"Determines whether or not n is positive, negative, or zero"
[n]
(cond
(< n 0) "negative"
(> n 0) "positive"
:else "zero"))
(pos-neg-or-zero 5)
(condp some [1 2 3 4]
#{0 6 7} :>> inc
#{4 5 9} :>> dec
#{1 2 3} :>> #(+ % 3))
(let [mystr "hello"]
(case mystr
"" 0
"hello" (count mystr)))
(when-some [x 1] [x :ok])
(if-some [a 10] :true :false)
In the next post, we'll continue with the comparison functions.