2011-12-12 98 views
1

我點的二維空間中的向量,例如:地圖矢量爲矢量散列Clojure中

[[0 0] [1 1] [2 2]] 

而且需要計算在向量一些點和每個點之間的距離,以確定哪個向量中的點最接近我正在查詢的點。我需要知道兩者的距離和最近點,所以我想這樣的散列的矢量:

[{:point [0 0] :dist 2.7} {:point [1 1] :dist 3.5} {:point [2 2] :dist 4.3}] 

我怎麼能轉換成前者後者?我想是這樣的:

(defn closest-point [point all-points] 
    (map #({:point % :dist (distance point %)}) all-points)) 

但我得到一個錯誤:

(user=> ArityException Wrong number of args (0) passed to: PersistentArrayMap clojure.lang.AFn.throwArity (AFn.java:437) 

回答

5

如果您使用for理解而不是map,這更易讀。此外,實際選擇最近的點,你可以用min-key

(defn closest-point [point all-points] 
    (apply min-key :dist 
     (for [p all-points] 
      {:point p :dist (distance point p)}))) 
9

#({...})擴展到(fn [] ({....}))它試圖調用地圖不帶任何參數。

試試這個:

(defn closest-point [point all-points] 
    (map (fn [p] {:point p :dist (distance point p)}) all-points)) 

(defn closest-point [point all-points] 
    (map #(hash-map :point % :dist (distance point %)) all-points)) 

(defn dist-info 
    [point p] 
    {:point p :dist (distance point p)}) 

(defn closest-point [point all-points] 
    (map #(dist-info point %) all-points)) 
+0

Joost的,謝謝。我有一個複製和粘貼錯誤,它忽略了我的哈希周圍的#(),我現在在問題中修正了這個錯誤。你的第二個解決方案完美運作如果您刪除開頭的段落和第一個示例(不起作用),我會接受您的回答。 –

+0

更新了我的答案 –

1
(defn closest-point [point all-points] 
    (map #(hash-map :point % :dist (distance point %)) all-points)                 

結果: -

({:point [0 0], :dist 2.7} {:point [1 1], :dist 3.5} {:point [2 2], :dist 4}) 
2

怎麼修復它,而不從您的代碼刪除任何東西,只是增加一個字:identity

(defn closest-point [point all-points] 
    (map #(identity {:point % :dist (distance point %)}) all-points))