Skip to content

Instantly share code, notes, and snippets.

@buntine
Created August 27, 2018 01:06
Show Gist options
  • Save buntine/51f9eb982f9b11e8b54e4ddedc2ff367 to your computer and use it in GitHub Desktop.
Save buntine/51f9eb982f9b11e8b54e4ddedc2ff367 to your computer and use it in GitHub Desktop.
Clojure for the Brave and True - Chapter 7 infix to prefix notation function
(defn expr-arrange [op]
(fn arrange [expr]
(cond
(<= (count expr) 2) expr
(= (second expr) op)
(conj (arrange (drop 3 expr))
(list (second expr) (first expr) (nth expr 2)))
:else (conj (arrange (rest expr)) (first expr)))))
(def multiply (expr-arrange '*))
(def divide (expr-arrange '/))
(def add (expr-arrange '+))
(def subtract (expr-arrange '-))
(defn infix [expr]
"Accepts a list containing a valid mathematical expression and returns an evaluatable expression
conforming to operator prescedence rules."
(-> expr
multiply
divide
add
subtract
first))
; Usage
(infix '(1 + 3 - 4))
(infix '(1 + 3))
(infix '(1))
(infix '(1 + 3 * 4 - 8))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment