Created
April 3, 2013 09:48
-
-
Save sortega/5299865 to your computer and use it in GitHub Desktop.
Check python indentation rules
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns pyindent.core) | |
(def tabsize 8) | |
(defn tabulate [column] | |
(- (+ column tabsize) | |
(rem column tabsize))) | |
(defn indent-level [^String line] | |
(let [[_ spaces] (re-matches #"^(\s*).*" line)] | |
(reduce (fn [level space] | |
((if (= \tab space) tabulate inc) | |
level)) | |
0 spaces))) | |
(defn non-empty? [^String line] | |
(not (.. line trim isEmpty))) | |
(defn increment [[level1 level2]] | |
(- level2 level1)) | |
(defn indentations [lines] | |
(->> lines | |
(filter non-empty?) | |
(map indent-level) | |
(cons 0) | |
(partition 2 1) | |
(map increment))) | |
(defn drop-upto [elem aseq] | |
(rest (drop-while #(not= elem %) | |
aseq))) | |
(defn valid-indentation? [lines] | |
(let [indents (indentations lines) | |
final-stack (reduce | |
(fn [stack indent] | |
(cond | |
(empty? stack) (reduced stack) | |
(pos? indent) (conj stack indent) | |
(neg? indent) (drop-upto (- indent) stack) | |
:else stack)) | |
(list 0) | |
indents)] | |
(and (zero? (first indents)) | |
(not (empty? final-stack))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment