Mosterd
Mosterd

Reputation: 151

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

Upvotes: 7

Views: 1598

Answers (2)

Paul Lam
Paul Lam

Reputation: 1819

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.

Upvotes: 1

dnolen
dnolen

Reputation: 18556

(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.

Upvotes: 5

Related Questions