Monads: Difference between revisions

From Rosetta Code
Content added Content deleted
(Created Monads page)
 
No edit summary
Line 2: Line 2:


1. Construct a Monad (preferably the Option/Maybe Monad)
1. Construct a Monad (preferably the Option/Maybe Monad)
2. Make two functions, each which take a number and return a wrapped number, and bind the two functions
2. Make two functions, each which take a number and return a wrapped number
3. Retrieve the result of calling the result of the bind
3. Compose the two functions with bind

=={{header|Clojure}}==

List Monad:

<lang clojure>
(defn bind [coll f] (apply vector (mapcat f coll)))
(defn unit [e] (vector e))

(def vecstr (comp vector str))
(defn doubler [n] [n n])

(bind (bind [3 4 5] vecstr) doubler) ; evaluates to ["3" "3" "4" "4" "5" "5"]
(-> [3 4 5]
(bind vecstr)
(bind doubler)) ; also evaluates to ["3" "3" "4" "4" "5" "5"]
</lang>

Revision as of 01:04, 30 January 2016

Demonstrate in your programming language the following:

 1. Construct a Monad (preferably the Option/Maybe Monad)
 2. Make two functions, each which take a number and return a wrapped number
 3. Compose the two functions with bind

Clojure

List Monad:

<lang clojure> (defn bind [coll f] (apply vector (mapcat f coll))) (defn unit [e] (vector e))

(def vecstr (comp vector str)) (defn doubler [n] [n n])

(bind (bind [3 4 5] vecstr) doubler) ; evaluates to ["3" "3" "4" "4" "5" "5"] (-> [3 4 5]

 (bind vecstr)
 (bind doubler)) ; also evaluates to ["3" "3" "4" "4" "5" "5"]

</lang>