Monads
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>
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...