Skip to content

Instantly share code, notes, and snippets.

@mavant
Created April 1, 2014 04:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mavant/9907685 to your computer and use it in GitHub Desktop.
Save mavant/9907685 to your computer and use it in GitHub Desktop.
(use '[clojure.string :as s])
(defn remove-whitespace "Given a string representing some Clojure code as input, remove superfluous whitespace." [c] (s/replace c #"\s+" " "))
(defn indent-levels "Given a list of lines of code, determine the appropriate number of tabs for each line." [l] (reduce (fn [a b] (conj a (+ (peek a) (if (= b ")") -1 1)))) [-1] l))
(defn remove-empty-lines "Given a list of strings, filters out any string which contains no word characters." [l] (filter (fn [c] (< 0 (count (re-seq #"\w" c)))) l))
(defn match-parens "Given a string of code, return a list of all the parentheses in the code, in the order in which they appear." [c] (re-seq #"[\)\(]" c))
(defn split-on-all-parens "Given a string of code, return a list split into parts by the locations of parentheses." [c] (s/split c #"[\)\(]"))
(defn parens->indents "Given a list of lines in which each begins an expression, prepends a newline and the appropriate number of tabs to each line." [c] (map (fn [a b] (str "\n" (apply str (repeat a "\t")) b)) (indent-levels (match-parens c)) (split-on-all-parens c)))
(def pythonize (comp (partial apply str) remove-empty-lines parens->indents remove-whitespace))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment