Skip to content

Instantly share code, notes, and snippets.

@shuaybi
Created May 8, 2011 18:14
Show Gist options
  • Select an option

  • Save shuaybi/961553 to your computer and use it in GitHub Desktop.

Select an option

Save shuaybi/961553 to your computer and use it in GitHub Desktop.
fnil
-------------------------
;clojure.core/fnil
;([f x] [f x y] [f x y z])
; Takes a function f, and returns a function that calls f, replacing
; a nil first argument to f with the supplied value x. Higher arity
; versions can replace arguments in the second and third
; positions (y, z). Note that the function f can take any number of
; arguments, not just the one(s) being nil-patched.
(+ nil 1)
;java.lang.NullPointerException (NO_SOURCE_FILE:0)
(def new+ (fnil + 0))
(new+ nil 1)
;EX-1
(def current-score {})
(defn update-score [current {:keys [country player score]}]
(update-in current [country player] + score))
(update-score current-score {:player "Paul Casey" :country :England :score -1})
;java.lang.NullPointerException (NO_SOURCE_FILE:0)
;FIX1
(defn update-score [current {:keys [country player score]}]
(update-in current [country player] #(+ (or %1 0) score)))
(update-score current-score {:player "Paul Casey" :country :England :score -1})
;=> {:England {"Paul Casey" -1}}
;FIX using fnil
(defn update-score [current {:keys [country player score]}]
(update-in current [country player] (fnil + 0) score))
(update-score current-score {:player "Paul Casey" :country :England :score -1})
;=> {:England {"Paul Casey" -1}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment