I'm looking for a Clojure library to do some basic geometry, such as:
I can write these quite easily, given the mathematical definitions of the equations, but it seems a shame to do so if there is a decent library out there that does this already.
Note that I don't need to plot things graphically and so on, so a library that introduces a lot of graphical dependencies is not really welcome.
I think in a case like this, seeing as the functions are so small, it is simpler just to write the functions than to introduce a dependency.
(defprotocol Line
(gradient [this] "The gradient of a line")
(intercept [this] "The intercept of a line on the y axis")
(f [this] "The line's function f(x) - takes x, returns y")
(f-inv [this] "The inverse function f-inv(x) - takes y, return x"))
(defn line
"Make a Line from a gradient and an intercept"
[gradient intercept]
(reify Line
(gradient [_] gradient)
(intercept [_] intercept)
(f [_] (fn [x] (+ (* gradient x) intercept)))
(f-inv [_] (fn [y] (/ (- y intercept) gradient)))))
(defn points->line
"Make a Line given two (different) points on the line"
[[x1 y1] [x2 y2]]
(let [gradient (/ (- y2 y1)
(- x2 x1))
intercept (- y1 (* gradient x1))]
(line gradient intercept)))
Example:
(def l (points->line [1 1] [4 2]))
(gradient l) ;=> 1/3
(intercept l) ;=> 2/3
((f l) 4) ;=> 2
((f-inv l) 2) ;=> 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With