Last active
April 18, 2018 16:44
-
-
Save jgomo3/d3ce3e1ade761dc24840054e0d8226c1 to your computer and use it in GitHub Desktop.
Last exercise of the Read and Eval Chapter of Brave Clojre
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 infix) | |
(defn index-of | |
"Clojure doesn't have an index-of function. The Java .indexOf method | |
works reliably for vectors and strings, but not for lists. This solution | |
works for all three. | |
https://stackoverflow.com/a/37858115/344501 | |
" | |
[item coll] | |
(let [v (if | |
(or (vector? coll) (string? coll)) | |
coll | |
(apply vector coll))] | |
(.indexOf coll item))) | |
(defn in? | |
"true if coll contains elm" | |
[coll elm] | |
(some #(= elm %) coll)) | |
(def precedences [['* '/] ['+ '-]]) | |
(def operators (flatten precedences)) | |
(defn extract-operator [l] | |
(filter #(in? operators %) l)) | |
(defn operator-grade [op] | |
(first (keep-indexed #(when (in? %2 op) [%1 op]) precedences))) | |
(defn max-op-of [l] | |
(last (apply max-key first (map operator-grade (extract-operator l))))) | |
(defn left-right-of [op l] | |
(let [op-pos (index-of op l) | |
[ll rl] (split-at op-pos l)] | |
[ll (rest rl)])) | |
(defn infix [l] | |
(if (= (count l) 1) | |
(first l) | |
(let | |
[max-op (max-op-of l) | |
[left-l right-l] (left-right-of max-op l)] | |
(list max-op (infix left-l) (infix right-l))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment