Clojure中的基本几何

Jos*_*ver 6 math geometry clojure

我正在寻找一个Clojure库来做一些基本的几何,例如:

  • 给出其起点和终点坐标的线的斜率
  • 给定具有已知斜率的线和x值,计算y值(并计算给定y的x)

考虑到方程的数学定义,我可以很容易地写出这些,但是如果有一个像样的库已经做到这一点,那么这样做似乎是一种耻辱.

请注意,我不需要以图形方式绘制事物等等,因此引入大量图形依赖项的库并不受欢迎.

Dan*_*eal 7

我认为在这样的情况下,看到函数是如此之小,编写函数比引入依赖更简单.

(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)))
Run Code Online (Sandbox Code Playgroud)

例:

(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
Run Code Online (Sandbox Code Playgroud)