Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 36 ยท Projects and Practice

Practice Problems

Twelve Clojure practice problems with hints and solutions: sequences, laziness, reduce, maps, recursion, atoms, macros and protocols, plus tips for solving them idiomatically.

You learn Clojure by writing Clojure. This lesson collects twelve exercises that reinforce the second half of the course: sequences, laziness, state, macros and protocols. Try each problem on paper or in a REPL before reading the hint, and only then the solution. There are several valid answers to most; the solutions show idiomatic ones.

Clojure code is read-only on this site, and you will need a local REPL for the original exercises (see tooling). Two runnable blocks at the end let you check the logic of several problems in JavaScript.

How to practice

  1. State the input and output in one sentence, and write an example as a test first.
  2. Prefer built-in sequence functions to hand-written loops (see sequence functions).
  3. Make the function work on small data at the REPL, then on bigger data.
  4. Compare with the solution and look for functions you did not know.

Part 1: Sequences and laziness

1. Collatz length. Write (collatz-length n): the number of steps for n to reach 1 by repeating "if even, halve; if odd, triple and add one". Hint: iterate plus take-while.

CLOJURE
(defn collatz-length [n]
  (->> (iterate #(if (even? %) (quot % 2) (inc (* 3 %))) n)
       (take-while #(not= % 1))
       count))

(collatz-length 6)   ;=> 8   (6 3 10 5 16 8 4 2 then 1)

2. Run-length encoding. (rle "aaabccdd") returns [["a" 3] ["b" 1] ["c" 2] ["d" 2]]. Hint: partition-by.

CLOJURE
(defn rle [s]
  (->> (partition-by identity s)
       (map (fn [run] [(str (first run)) (count run)]))
       vec))

3. Lazy primes. Produce an infinite lazy sequence of primes. Hint: a number is prime if no earlier prime up to its square root divides it.

CLOJURE
(def primes
  (cons 2
        (filter (fn [n]
                  (not-any? #(zero? (mod n %))
                            (take-while #(<= (* % %) n) primes)))
                (iterate #(+ % 2) 3))))

(take 8 primes)   ;=> (2 3 5 7 11 13 17 19)

The sequence refers to itself, which works because the tail is lazy.

4. Anagram groups. Given a list of words, group those that are anagrams of each other. Hint: group-by on the sorted letters.

CLOJURE
(defn anagram-groups [words]
  (->> (group-by sort words)
       vals
       (filter #(> (count %) 1))))

(anagram-groups ["listen" "silent" "enlist" "google" "gogole" "cat"])
;=> (["listen" "silent" "enlist"] ["google" "gogole"])

Part 2: Data and reduce

5. Merge inventories. Combine two maps of item counts, adding counts for shared keys. Hint: merge-with.

CLOJURE
(merge-with + {:pen 2 :ink 1} {:pen 3 :cap 4})
;=> {:pen 5, :ink 1, :cap 4}

6. Deep get-or-default. Write (dig m path default) that works like get-in but returns default when the path exists with value nil. Hint: contains? on the last step, or get-in with a sentinel.

CLOJURE
(defn dig [m path default]
  (let [sentinel (Object.)
        v (get-in m path sentinel)]
    (if (identical? v sentinel) default v)))

7. Flatten one level of a nested map. Turn {:a {:x 1 :y 2} :b {:z 3}} into {[:a :x] 1, [:a :y] 2, [:b :z] 3}. Hint: for with two bindings, then into {}.

CLOJURE
(defn flatten-map [m]
  (into {} (for [[k inner] m, [k2 v] inner] [[k k2] v])))

8. Running maximum. (running-max [3 1 4 1 5 9 2]) gives [3 3 4 4 5 9 9]. Hint: reductions with max.

CLOJURE
(defn running-max [xs] (vec (reductions max xs)))

Part 3: State and concurrency

9. Rate limiter. Create (allow? limiter) that returns true at most 3 times and then false, using an atom. Hint: swap-vals! returns old and new values, so you can decide from the old.

CLOJURE
(defn make-limiter [n] (atom n))

(defn allow? [limiter]
  (let [[old _] (swap-vals! limiter #(max 0 (dec %)))]
    (pos? old)))

(let [l (make-limiter 3)]
  (repeatedly 5 #(allow? l)))
;=> (true true true false false)

10. Parallel sum. Sum the squares of 1 to 1,000,000 by splitting into chunks and using pmap, then compare with a plain reduce. Hint: partition-all produces chunks; (apply + (pmap chunk-sum chunks)) combines them. Measure with time. Expect plain reduce to be competitive for cheap work: parallelism needs chunks big enough to pay for itself (futures and pmap).

Part 4: Macros and protocols

11. A my-or macro that short-circuits and evaluates each argument once, like or. Hint: bind to a gensym.

CLOJURE
(defmacro my-or
  ([] nil)
  ([x] x)
  ([x & more] `(let [t# ~x] (if t# t# (my-or ~@more)))))

(my-or nil false 3 (println "never"))   ;=> 3

12. A Describable protocol with describe implemented for a record Person and for nil, and extended to Java's String. Hint: defprotocol, defrecord, extend-protocol (protocols).

CLOJURE
(defprotocol Describable (describe [x]))

(defrecord Person [name age]
  Describable
  (describe [p] (str name ", age " age)))

(extend-protocol Describable
  nil    (describe [_] "nothing")
  String (describe [s] (str "text: " s)))

(map describe [(->Person "Ana" 30) nil "hi"])
;=> ("Ana, age 30" "nothing" "text: hi")

Try it: check the logic in JavaScript

JS Problems 1, 2, 4 and 8

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Try it: problems 3, 5, 9 and 7

JS Primes, merge-with, limiter, flatten-map

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Where to go next

  • Rebuild one of the projects with a different tool: transducers, an agent, or a core.async pipeline.
  • Solve problems from collections such as 4Clojure-style puzzles and Advent of Code in Clojure; limit yourself to the standard library at first.
  • Read the source of core functions with (source name); some, partition-by and group-by are short and instructive.
  • Write a small web service with Ring and Reitit, or a ClojureScript front end, once the fundamentals feel natural.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which function gives the most direct solution to run-length encoding?

    partition-by splits a sequence into runs where the function's result stays the same.
  2. 2. Why does the self-referential primes definition work?

    filter returns a lazy sequence; elements are only realized when requested, by which time primes exists.
  3. 3. What makes swap-vals! useful for the rate limiter?

    Reading the atom separately and then swapping would be a race; swap-vals! gives both values from one atomic step.
  4. 4. How should you solve a practice problem first?

    Trying first, with an example to check, is what builds fluency.

Summary

  • Idiomatic solutions lean on iterate, partition-by, group-by, merge-with, reductions and for rather than manual loops.
  • Lazy, self-referential sequences are valid because realization is on demand.
  • swap-vals! makes read-and-update decisions atomic; parallelism pays only for sufficiently heavy work.
  • Macros should evaluate each argument once; protocols extend to nil, strings and your own records.
  • Keep practicing with small tests at the REPL.

Back to the track: Clojure