Skip to content

Instantly share code, notes, and snippets.

@chrisbarrett
Last active December 20, 2015 05:08
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 chrisbarrett/6075549 to your computer and use it in GitHub Desktop.
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.
(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