Monads

From Rosetta Code
Revision as of 11:00, 30 January 2016 by rosettacode>Domgetter (→‎{{header|Clojure}}: remove colons from subsection headers in Clojure section)

Demonstrate in your programming language the following:

  1. Construct a Monad (preferably the Option/Maybe Monad or the List Monad) by making bind and unit for that Monad (or just use what the language already has implemented)
  2. Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String
  3. Compose the two functions with bind

Clojure

Maybe Monad

<lang clojure> (defn bind [val f] (if (nil? (:value val)) val (f (:value val)))) (defn unit [val] {:value val})

(defn opt_add_3 [n] (unit (+ 3 n))) ; takes a number and returns a Maybe number (defn opt_str [n] (unit (str n)))  ; takes a number and returns a Maybe string

(bind (unit 4) opt_add_3)  ; evaluates to {:value 7} (bind (unit nil) opt_add_3)  ; evaluates to {:value nil} (bind (bind (unit 8) opt_add_3) opt_str)  ; evaluates to {:value "11"} (bind (bind (unit nil) opt_add_3) opt_str) ; evaluates to {:value nil} </lang>

List Monad

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

(defn doubler [n] [(* 2 n)])  ; takes a number and returns a List number (def vecstr (comp vector str)) ; takes a number and returns a List string

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

 (bind doubler)
 (bind vecstr)) ; also evaluates to ["6" "8" "10"]

</lang>

J

Note that J documentation mentions "monad" but that is an older (much older) use of the term from what is intended here. J documentation uses "box" <to describe the operation mentioned here.

So, here are two functions which each take a number and return a wrapped number:

<lang j>f=: < g=: <</lang>

And here are the two functions composed together:

<lang j>f@g</lang>

That said J does not, by default, implicitly choose function implementation (which is probably what was implied in this context). But let's wait for the task description to explicitly call for that before trying to address that issue...