Skip to content

Instantly share code, notes, and snippets.

@cark
Created September 7, 2012 16:34
Show Gist options
  • Save cark/3667614 to your computer and use it in GitHub Desktop.
Save cark/3667614 to your computer and use it in GitHub Desktop.
state-m fetch-val bug and efficiency issue
;; the bug
(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))) ;; only works for keyword keys
;; I propose replacing it with (get s key)
;; the efficiency issue
;; domonad binds all the monad functions, looking these up in the state-m map on each call
;; 5 solutions :
(defmonadfn my-fetch-val1 [key]
(m-bind (fetch-state) #(m-result (get % key))))
(defmonadfn my-fetch-val2 [key]
(domonad
[s (fetch-state)]
(get s key)))
(with-monad state-m
(defn my-fetch-val3 [key]
(m-bind (fetch-state) #(m-result (get % key))))
(defn my-fetch-val4 [key]
(domonad
[s (fetch-state)]
(get s key))))
(defn my-fetch-val5 [key]
(fn [s]
[(get s key) s]))
;; my-fetch-val5 is my preferred solution, as its style
;; is consistent with the rest of the state functions
;; and i believe it is the most efficient
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment