Last active
December 20, 2015 05:08
-
-
Save chrisbarrett/6075549 to your computer and use it in GitHub Desktop.
Macro for writing math expressions with infix syntax. Requires calc, smartparens, dash and s.
This file contains hidden or 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
(defmacro cal (&rest expression) | |
"Evaluate algebraic EXPRESSION using calc." | |
(let* | |
((expr (with-temp-buffer | |
(lisp-mode) | |
(insert (->> expression | |
(-map 'pp-to-string) | |
(apply 'concat) | |
(s-replace (rx space) ""))) | |
;; Unpack unquote forms applied by the lisp reader. | |
(goto-char (point-min)) | |
(while (search-forward "(\\," nil t) | |
(forward-char -1) | |
(sp-splice-sexp-killing-around)) | |
(buffer-string))) | |
(result (calc-eval expr))) | |
(if (listp result) | |
(destructuring-bind (pos err) result | |
(error "%s\n%s\n%s^" | |
err | |
expr | |
(s-repeat pos " "))) | |
(read (s-replace "," "" result))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment