Skip to content

Instantly share code, notes, and snippets.

@divs1210
Last active June 22, 2021 22:20
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save divs1210/b4fcbd48d7697dfd8850 to your computer and use it in GitHub Desktop.
Save divs1210/b4fcbd48d7697dfd8850 to your computer and use it in GitHub Desktop.
(ns maya)
(defmacro math->
" (math-> 1 + 5 * 2 / 3) ;=> (-> 1 (+ 5) (* 2) (/ 3)) ;=> 4 "
[exp & f-x-pairs]
(if (even? (count f-x-pairs))
`(-> ~exp
~@(for [[f x] (partition 2 f-x-pairs)]
(list f x)))
(throw (Exception. "f-x-pairs should be even."))))
(defmacro maya
" (maya 1 + 5 :as six, six * 2 :as twelve, twelve / 3 * 2) ;=> 8 "
[& exprs]
(let [[exp [_ ?as & next-exprs :as E]] (split-with #(not= :as %) exprs)]
(if (empty? E)
(cons `math-> exp)
`(let [~?as (math-> ~@exp)]
(maya ~@next-exprs)))))
(comment
;-----
;Usage
;-----
(defn df [f]
(fn [x]
(maya 0.0001 :as dx, x + dx :as x+, (f x+) - (f x) / dx)))
(defn quadratic [a b c]
(maya 4 * a * c :as d,
b * b - d Math/pow 0.5 :as D,
2 * a :as t, (- b) :as -b,
-b + D / t :as x1,
-b - D / t :as x2,
[x1 x2]))
;------------------
;Python equivalents
;------------------
def df(f):
def g(x):
dx = 0.0001
return (f(x+dx) - f(x)) / dx
return g
def quadratic(a, b, c):
d = 4 * a * c
D = (b**2 - d) ** 0.5
t = 2 * a
return [(-b + D) / t, (-b - D) / t]
)
@divs1210
Copy link
Author

divs1210 commented Jan 8, 2015

I wrote a blog post on this. if anyone's interested.

Or follow the discussion at Hacker News.

@jarcane
Copy link

jarcane commented Jan 8, 2015

This is very very nice. Would you mind awfully if I tried porting this to Heresy?

@divs1210
Copy link
Author

divs1210 commented Jan 8, 2015

Please go ahead. And don't forget to post a link here!

@jarcane
Copy link

jarcane commented May 26, 2015

We've implemented our version for Heresy now. No docs yet, but the tests should be demonstrative. https://github.com/jarcane/heresy/blob/master/tests/infix-math.rkt

And the code, in a mix of Heresy and Racket. https://github.com/jarcane/heresy/blob/master/lib/infix-math.rkt

@divs1210
Copy link
Author

divs1210 commented Aug 2, 2015

NOTE: maya is now available as a library.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment