导航传染媒介传染媒介对在Clojure的哈希传染媒介

时间:2011-12-12 08:33:43

标签: clojure functional-programming

我在2D空间中有一个点矢量,例如:

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

4 个答案:

答案 0 :(得分: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))

答案 1 :(得分: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)})))

答案 2 :(得分:2)

如果要修改它而不从代码中删除任何内容,只需添加一个单词:identity

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

答案 3 :(得分: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})