2014-03-02 28 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

非常好的東西,謝謝! –