(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] | |
) |
This comment has been minimized.
This comment has been minimized.
This is very very nice. Would you mind awfully if I tried porting this to Heresy? |
This comment has been minimized.
This comment has been minimized.
Please go ahead. And don't forget to post a link here! |
This comment has been minimized.
This comment has been minimized.
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 |
This comment has been minimized.
This comment has been minimized.
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
This comment has been minimized.
I wrote a blog post on this. if anyone's interested.
Or follow the discussion at Hacker News.