Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic geometry in Clojure [closed]

I'm looking for a Clojure library to do some basic geometry, such as:

  • Calculating the slope of a line given its starting and ending coordinates
  • Given a line with a known slope, and an x value, calculating the y value (and calculating x given y)

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.

like image 848
Josh Glover Avatar asked Mar 02 '14 11:03

Josh Glover


1 Answers

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
like image 53
Daniel Neal Avatar answered Nov 03 '22 00:11

Daniel Neal