2014-03-02 31 views
6
基本几何

我正在寻找一个Clojure的库做一些基本的几何形状,如:Clojure中

  • 计算一个直线的斜率赋予其起点和终点坐标
  • 给定一个行以众所周知坡度和x值,计算y值(和计算的x给出Y)

我能给出的公式的数学定义,写这些很容易,但它似乎是一个耻辱这样做,如果有是一个体面的图书馆,已经这样做了。

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

+1

如果你不能找到它的[GitHub的(?https://github.com/clojure)或[Clojars(https://clojars.org/search?q = geometry),那么它可能不存在。为什么不创建一个? – ChrisDevo

+0

看起来我可能不得不自己滚动它,因为我还没有找到任何东西。 –

+2

https://github.com/danielgrigg/sligeom上有一些代码,尽管我没有时间去查看这是否是您需要的。如果是这样,请用它回答你自己的问题。 HTH – ClojureMostly

回答

6

我认为在这样的情况下,由于功能太小,仅仅编写函数比引入依赖关系更简单。

(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))) 

例子:

(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 
+1

非常好的东西,谢谢! –