August 12, 2018
4clojure 135 - Infix Calculator
Your friend Joe is always whining about Lisps using the prefix notation for math. Show him how you could easily write a function that does math using the infix notation. Is your favorite language that flexible, Joe? Write a function that accepts a variable length mathematical expression consisting of numbers and the operations +, -, *, and /. Assume a simple calculator that does not do precedence and instead just calculates left to right.
(ns live.test
(:require [cljs.test :refer-macros [deftest is run-tests]]))
(defn infix [a & r]
(reduce
(fn [a [op b]] (op a b))
a (partition 2 r)))
(deftest test-135
(is (= 7 (infix 2 + 5)))
(is (= 42 (infix 38 + 48 - 2 / 2)))
(is (= 8 (infix 10 / 2 - 1 * 2)))
(is (= 72 (infix 20 / 2 + 2 + 4 + 8 - 6 - 10 * 9))))
(run-tests)