I am new to clojure and the main thing I am struggling with is writing readable code. I often end up with functions like the one below.
(fn rep
([lst n]
(rep (rest lst)
n
(take n
(repeat (first lst)))))
([lst n out]
(if
(empty? lst)
out
(rep
(rest lst) n
(concat out (take n
(repeat
(first lst))))))))
with lots of build ups of end brackets. What are the best ways of reducing this or formatting it in a way that makes it easier to spot missing brackets?
Using Emacs's paredit
mode (emulated in a few other editors too) means you're generally - unless you're copy/pasting with mouse/forced-unstructured selections - dealing with matched brackets/braces/parentheses and related indenting with no counting needed.
Emacs with https://github.com/technomancy/emacs-starter-kit (highly recommended!) has paredit enabled for clojure by default. Otherwise, see http://emacswiki.org/emacs/ParEdit
In addition to having an editor that supports brace matching, you can also try to make your code less nested. I believe that your function could be rewritten as:
(defn rep [coll n] (mapcat (partial repeat n) coll))
Of course this is more of an art (craft) than science, but some pointers (in random order):
chouser
->
and ->>
threading macros are very useful for flattening nested codeAn editor that colors the parenthesis is extremely helpful in this case. For example, here's what your code looks in my vim editor (using vimclojure):
Since you didn't say which editor you use, you'll have to find the rainbow-coloring feature for your editor appropriately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With