is this a simple monad example?

Posted by zcaudate on Stack Overflow See other posts from Stack Overflow or by zcaudate
Published on 2012-09-08T09:36:50Z Indexed on 2012/09/08 9:37 UTC
Read the original article Hit count: 239

Filed under:
|

This is my attempt to grok monadic functions after watching http://channel9.msdn.com/Shows/Going+Deep/Brian-Beckman-Dont-fear-the-Monads.

h uses bind to compose together two arbitrary functions f and g. What is the unit operator in this case?

;; f :: int -> [str]
;; g :: str => [keyword]
;; bind :: [str] -> (str -> [keyword]) -> [keyword]
;; h :: int -> [keyword]

(defn f [v]
  (map str (range v)))

(defn g [s]
  (map keyword (repeat 4 s)))

(defn bind [l f]
  (flatten
   (map f l)))

(f 8) ;; => (0 1 2 3 4 5 6 7)
(g "s") ;; => (:s :s :s :s)

(defn h [v]
  (bind (f v) g))

(h 9) 
;; => (:0 :0 :0 :0 :1 :1 :1 :1 :2 :2 :2 :2 :3 :3 :3 :3 :4 :4 :4 :4 :5 :5 :5 :5)

© Stack Overflow or respective owner

Related posts about clojure

Related posts about monads