Skip to content

Instantly share code, notes, and snippets.

@teepark
Last active January 22, 2016 23:46
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 teepark/320c547d7fbd86ff8a8a to your computer and use it in GitHub Desktop.
Save teepark/320c547d7fbd86ff8a8a to your computer and use it in GitHub Desktop.
exact.clj
(defn exactify
"take a multi-arity function and convert it to one that rationalizes all its arguments"
[f]
(fn
([] (f))
([x] (f (rationalize x)))
([x & items] (loop
[agg (rationalize x)
items items]
(if (empty? items)
agg
(recur (f agg (rationalize (first items))) (rest items)))))))
(defmacro exact
"change an arithmetic operation to only operate on rational numbers"
[form]
`(let
[+ (exactify +)
- (exactify -)
* (exactify *)
/ (exactify /)]
~form))
(macroexpand '(exact (* 2452.45 100)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment