Created
April 10, 2021 11:33
-
-
Save Crowbrammer/826510163e403c8411e2b2710393c034 to your computer and use it in GitHub Desktop.
Multiply with infix notation in Clojure
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
(defn pem-helper [sq symb] | |
(loop [tail sq i 0] | |
(if (seq tail) | |
(if (= (first tail) symb) | |
i | |
(recur (rest tail) (inc i))) | |
nil))) | |
(defn pem-mult-i [sq] | |
(pem-helper sq '*)) | |
(defn pem-div-i [sq] | |
(pem-helper sq '/)) | |
(defn pem-add-i [sq] | |
(pem-helper sq '+)) | |
(defn pem-minus-i [sq] | |
(pem-helper sq '-)) | |
(defn pemdas-i [sq] | |
(cond | |
(some #(= % '*) sq) (pem-mult-i sq) | |
(some #(= % '/) sq) (pem-div-i sq) | |
(some #(= % '+) sq) (pem-add-i sq) | |
(some #(= % '-) sq) (pem-minus-i sq) | |
:else nil)) | |
(defn bunch [sq i] | |
(let [fir (take (dec i) sq) | |
bunch (list (nth sq i) (nth sq (dec i)) (nth sq (inc i))) | |
rema (drop (inc (inc i)) sq)] | |
(concat (concat fir (list bunch)) rema))) | |
(defmacro my-infix [infix] | |
(loop [cur infix] | |
(let [i (pemdas-i cur)] | |
(if i | |
(recur (bunch cur i)) | |
(first cur))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment