Skip to content

Instantly share code, notes, and snippets.

@roman
Created December 8, 2011 19:40
Show Gist options
  • Save roman/1448218 to your computer and use it in GitHub Desktop.
Save roman/1448218 to your computer and use it in GitHub Desktop.
Playing with clojure monads
(ns playground.monad
(:use [clojure.algo.monads :only
[domonad defmonadfn with-monad state-m fetch-state set-state
update-state m-fmap]]))
(def get-name
(domonad state-m
[a (fetch-state)]
(:name a)))
(defn upper [s]
(.toUpperCase s))
(def scream
(domonad state-m
[a-name get-name]
(upper a-name)))
(defmonadfn screaming-title [s]
(m-bind get-name
(comp m-result (partial str s " - ") upper)))
;
; To run screaming-title
; ((with-monad state-m
; (screaming-title "hello")) {:name "roman"})
; -> "hello - ROMAN"
;
; In order to run this function we need to use the with-monad call, this
; because the function is using m-bind and m-result as abstract functions.
;------------------------------------------------------------------------------
; To run scream
; (scream {:name "esse"})
; -> "ESSE"
;
; This function doesn't require the with-monad call, given that we already
; binded the domonad.
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment