Last active
June 22, 2021 22:20
-
-
Save divs1210/b4fcbd48d7697dfd8850 to your computer and use it in GitHub Desktop.
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
(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 is very very nice. Would you mind awfully if I tried porting this to Heresy?
Please go ahead. And don't forget to post a link here!
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
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
I wrote a blog post on this. if anyone's interested.
Or follow the discussion at Hacker News.