Last active
December 17, 2015 10:59
-
-
Save maio/5599206 to your computer and use it in GitHub Desktop.
Monads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns monads.core | |
(:use [clojure.algo.monads | |
:only (domonad with-monad m-lift m-seq m-reduce m-when | |
identity-m | |
sequence-m | |
maybe-m | |
state-m fetch-state set-state | |
writer-m write | |
cont-m run-cont call-cc | |
maybe-t)])) | |
;; identity monad | |
(with-monad identity-m (m-bind 10 inc)) | |
;; sequence monad | |
(with-monad sequence-m (m-bind [1 2 3] (fn [x] [(inc x)]))) | |
(with-monad sequence-m | |
(m-bind [1 2 3] (fn [x] | |
(m-bind [4 5 6] (fn [y] [x y]))))) | |
(domonad sequence-m | |
[x [1 2 3] | |
y [4 5 6]] | |
[x y]) | |
(for [x [1 2 3] | |
y [4 5 6]] | |
[x y]) | |
;; maybe monad | |
(reduce + [1 nil 3]) ;; => Null Pointer Exception | |
(with-monad maybe-m | |
(m-reduce + [1 nil 3])) ;; => nil | |
(domonad maybe-m | |
[x 1 | |
y 2 | |
z 3] | |
(+ x y z)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment