Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly indent clojure/lisp?

I want to indent the following piece of code. How would a lisper indent this? I am especially confused about where to put newlines.

(defn primes [n]
  (letfn [(sieve [table removal]
                 (assoc table removal false))
          (primebools [i table]
                       (cond 
                         (= i n) table 
                         (table i) (recur (inc i) 
                                          (reduce sieve 
                                                  table 
                                                  (range (* i i) n i))) 
                         :else (recur (inc i) 
                                      table)))]
    (let [prime? (primebools 2 (apply vector (repeat n true)))]
      (filter prime? (range 2 n)))))
like image 851
Mosterd Avatar asked Jun 13 '11 20:06

Mosterd


2 Answers

(defn primes [n]
  (letfn [(sieve [table removal]
            (assoc table removal false))
          (primebools [i table]
            (cond 
              (= i n) table 
              (table i) (recur (inc i) 
                          (reduce sieve table 
                            (range (* i i) n i))) 
              :else (recur (inc i) table)))]
    (let [prime? (primebools 2 (apply vector (repeat n true)))]
      (filter prime? (range 2 n)))))

Is how I would do it.

like image 71
dnolen Avatar answered Nov 21 '22 00:11

dnolen


In addition to @dnolen's answer, I usually put a new line when there's

  1. a new function (like your first two lines)
  2. to indent long or important argument to a function (like the cond block)
  3. logically keep each line to less than 80 characters and break up long ideas to smaller chunks
  4. most importantly, be consistent!

Then just align and indent lines so that the identations are for the same depth of code.

like image 1
Paul Lam Avatar answered Nov 20 '22 22:11

Paul Lam