MLev
MLev

Reputation: 435

Clojure Null Pointer Exception Due to Function Key Mismatch

I am working through the beginning of a Clojure for the Brave and True example:

(ns the-divine-cheese-code.visualization.svg
  (:require [clojure.string :as s])
  (:refer-clojure :exclude [min max]))

(defn comparator-over-maps
  [comparison-fn ks]
  (fn [maps]
    (zipmap ks
            (map (fn [k] (apply comparison-fn (map k maps)))
                 ks))))

(def min (comparator-over-maps clojure.core/min [:lat :lng]))
(def max (comparator-over-maps clojure.core/max [:lat :lng]))

I am getting a Null Pointer Exception, though, when I try to run the following code in a CIDER REPL:

(min [{:a 1 :b 3} {:a 5 :b 0}])

I am trying to identify the source of the error within the code. Any help would certainly be appreciated.

Upvotes: 1

Views: 239

Answers (2)

MLev
MLev

Reputation: 435

Based on @BlackBear's comment, I reran the code in the CIDER REPL as:

(min [{:lat 1 :lng 3} {:lat 5 :lng 0}])

and it produced the correct answer:

=> {:lat 1, :lng 0}

Thanks for your help!

Upvotes: 0

Logan Buckley
Logan Buckley

Reputation: 211

The function comparator-over-maps uses the vector of keywords that you pass it to look up values in the map. In this case the maps you're passing have keys :a and :b, but your definition of min is requesting the keys :lat and :lng, which don't exist -- so it receives nil, which is the cause of the NPE. If you change one or the other set of keywords to match, then the example should work, e.g.:

(min [{:lat 1 :lng 3} {:lat 5 :lng 0}])

Upvotes: 3

Related Questions