WorldsEndless
WorldsEndless

Reputation: 1494

Clojure NullPointerException with sort-by

Is this a bug or can I fix it somehow? (of course in my live code the similarity number is computed)

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

Using Clojure 1.6.0, Fedora 20x64, standard REPL.

ADDED Why do I get that failure, but in (what I would expect to be analogous) this I'm okay:

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"})

Upvotes: 0

Views: 219

Answers (2)

user100464
user100464

Reputation: 18469

I think this is your problem:

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

Upvotes: 0

Leonid Beschastny
Leonid Beschastny

Reputation: 51490

You can't access vector elements by keyword, only by their index:

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

So, you should use hashmap instead:

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

Here is how your code should look:

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

Upvotes: 3

Related Questions