How to properly indent clojure/lisp?
Asked Answered
B

2

7

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)))))
Bracci answered 13/6, 2011 at 20:25 Comment(1)
When in doubt about indentation, paste it into Emacs in clojure-mode and use C-M-q. Put newlines wherever feels good.Dinnerware
S
5
(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.

Shore answered 13/6, 2011 at 20:41 Comment(1)
I would indent the arguments to recur to the same column.Indigotin
A
1

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.

Andra answered 13/6, 2011 at 20:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.