开发者

Is this Clojure code indented properly?

http://pastebin.com/d2294a374

I've posted code indented in 2 different way in there. I get confused here because I am not sure what to do when a function has multiple arguments. Should each argument be on a different line or the same? furthermore, when we have something like (def xyz (fn abc [a1 a2] ... does (fn abc ... go in a different line?

I am reading the following from http://mumble.net/~campbell/scheme/style.txt, but it does not seem to make much sense to me.

** Indentation and Alignment

The operator of any form, i.e. the first subform following the opening round bracket, determines the rules for indenting or aligning the remaining forms. Many names in this position indicate special alignment or indentation rules; these are special operators, macros, or procedures that have certain parameter structures.

If the first subform is a non-special name, however, then if the second subform is on the same line, align the starting column of all following subforms with that of the second 开发者_运维知识库subform. If the second subform is on the following line, align its starting column with that of the first subform, and do the same for all remaining subforms.

In general, Emacs will indent Lisp code correctly. Run `C-M-q' (indent-sexp) on any code to ensure that it is indented correctly, and configure Emacs so that any non-standard forms are indented appropriately.

Unacceptable:

(+ (sqrt -1)
  (* x y)
  (+ p q))

(+
   (sqrt -1)
   (* x y)
   (+ p q))

Acceptable:

(+ (sqrt -1)
   (* x y)
   (+ p q))

(+
 (sqrt -1)
 (* x y)
 (+ p q))

Rationale: The columnar alignment allows the reader to follow the operands of any operation straightforwardly, simply by scanning downward or upward to match a common column. Indentation dictates structure; confusing indentation is a burden on the reader who wishes to derive structure without matching parentheses manually.


If arguments are on multiple lines (e.g. because they don't fit on one line), they should all have the same indentation. If you put the first argument on a new line, that indentation should be one deeper (e.g. 2 spaces) than that of the function itself:

(foo (bar (baz
            arg1
            arg2)))

If you put the first argument on the same line as the function, the rest should have the same indentation:

(foo (bar (baz arg1
               arg2)))

I'd indent your example as follows:

(defn get-neighbors [[x y] v]
  (for [y1 (range (dec y) (+ y 2))
        x1 (range (dec x) (+ x 2))
        :when (and (not (and (= x1 x)
                             (= y1 y)))
                   (in-bounds? x1 y1 v))]
    ((v y1) x1)))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜