From 6e6458f8af37a6e1074e8067e52eb3e231fff825 Mon Sep 17 00:00:00 2001 From: David Barksdale Date: Wed, 2 Feb 2011 16:27:58 -0800 Subject: The state monad's fetch-val and update-val now accept a zero argument in case the state does not contain the given key. Just as before, the zero defaults to nil. --- src/main/clojure/clojure/contrib/monads.clj | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/main/clojure/clojure/contrib/monads.clj b/src/main/clojure/clojure/contrib/monads.clj index d164f7eb..a268e778 100644 --- a/src/main/clojure/clojure/contrib/monads.clj +++ b/src/main/clojure/clojure/contrib/monads.clj @@ -367,20 +367,25 @@ (defn fetch-val "Return a state-monad function that assumes the state to be a map and returns the value corresponding to the given key. The state is not modified." - [key] - (domonad state-m - [s (fetch-state)] - (key s))) + ([key] + (fetch-val key nil)) + ([key zero] + (domonad state-m + [s (fetch-state)] + (get s key zero)))) (defn update-val "Return a state-monad function that assumes the state to be a map and replaces the value associated with the given key by the return value of f applied to the old value. The old value is returned." - [key f] - (fn [s] - (let [old-val (get s key) - new-s (assoc s key (f old-val))] - [old-val new-s]))) + ([key f] + (update-val key nil f)) + ([key zero f] + (fn [s] + (let [old-val (get s key zero) + new-s (assoc s key (f old-val))] + [old-val new-s])))) + (defn set-val "Return a state-monad function that assumes the state to be a map and -- cgit v1.2.3-18-g5258