Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managing number of brackets in clojure

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?

like image 796
Jim Jeffries Avatar asked Apr 10 '12 19:04

Jim Jeffries


3 Answers

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

like image 101
Joost Diepenmaat Avatar answered Oct 08 '22 09:10

Joost Diepenmaat


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):

  • Problems on 4clojure and their solutions by top users (visible after solving particular problems) - I believe that Chris Houser is there under the handle chouser
  • Speaking of CH - "The Joy of Clojure" is a very useful read
  • Browsing docs on clojure.core - there are a lot of useful functions there
  • -> and ->> threading macros are very useful for flattening nested code
  • stackoverflow - some of the brightest and most helpful people in the world answer questions there ;-)
like image 28
Rafał Dowgird Avatar answered Oct 08 '22 09:10

Rafał Dowgird


An 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):

Rainbow colors

Since you didn't say which editor you use, you'll have to find the rainbow-coloring feature for your editor appropriately.

like image 34
Jeff Avatar answered Oct 08 '22 07:10

Jeff