Clojure NullPointerException with sort-by

时间:2014-10-02 14:16:11

标签: sorting exception clojure

这是一个错误还是我能以某种方式修复它? (当然在我的实时代码中计算相似度)

(sort-by :similarity > (for [ob [:a :b :c]] [:object ob :similarity 0.0]))
NullPointerException   clojure.lang.Numbers.ops (Numbers.java:961)

使用Clojure 1.6.0,Fedora 20x64,标准REPL。

ADDED 为什么我会失败,但在(我希望是类似的)这个我没关系:

user=> (sort-by :similarity > [{:shape "circle" :similarity 1.0}{:shape "square" :similarity 0.5}{:shape "triangle" :similarity 0.0}])
({:similarity 1.0, :shape "circle"} {:similarity 0.5, :shape "square"} {:similarity 0.0, :shape "triangle"})

2 个答案:

答案 0 :(得分:3)

您无法通过关键字访问向量元素,只能按索引访问:

=> (get [:similarity 0.5] :similarity)
nil
=> (get [:similarity 0.5] 1)
0.5

所以,你应该使用hashmap:

=> (get {:similarity 0.5} :similarity)
0.5

以下是您的代码的外观:

(sort-by :similarity > (for [ob [:a :b :c]] {:object ob :similarity 0.0}))

答案 1 :(得分:0)

我认为这是你的问题:

=> (map :similarity (for [ob [:a :b :c]] [:object ob :similarity 0.0]))
(nil nil nil)
=> (for [ob [:a :b :c]] [:object ob :similarity 0.0])
([:object :a :similarity 0.0] [:object :b :similarity 0.0] [:object :c :similarity 0.0])