1

I am trying to wrap my head around the sequence monad in query.

I have this code that creates a sequence monad using clojure.algo.monads:

(use 'clojure.algo.monads)

(def sequence-monad-decider
     (fn [step-value monadic-continuation]
       (mapcat monadic-continuation step-value)))

(def sequence-monad-monadifier list)

(def sequence-monad
     (monad [m-result sequence-monad-monadifier
             m-bind sequence-monad-decider]))

(prn
 (with-monad sequence-monad
   (domonad [a [1 2]
             b [10, 100]
             c [-1 1]]
            (* a b c))))

So I understand that m-bind will be used to pass a step value and a continuation to sequence-monad-decider.

sequence.monad-decider is defined like this:

(def sequence-monad-decider
     (fn [step-value monadic-continuation]
       (mapcat monadic-continuation step-value)))

so if we look at calling the monad:

(prn
 (with-monad sequence-monad
   (domonad [a [1 2]
             b [10, 100]
             c [-1 1]]
            (* a b c))))

With binding a of the above, [1 2] will be passed as the step value to sequence.monad.decider but what is the monadic-continuation function that is passed as the second argument to this function?

dagda1
  • 26,856
  • 59
  • 237
  • 450

1 Answers1

1

More typical names for sequence-monad-decider and sequence-monad-monadifier are bind and either result, return, or unit.

(defn bind [mv f] (mapcat f mv)) 
(defn unit [v] [v])

Then

 (domonad sequence-m
   [a [1 2]
    b [10, 100]
    c [-1 1]]
   (* a b c))

Is

 (bind [1 2] 
       (fn [a] 
         (domonad sequence-m
           [b [10, 100]
            c [-1 1]]
           (* a b c))))

Try it! So, the second argument, which you have aptly named as monadic-continuation, is the continuation of the monad, the rest of the action.

If you carried this out, you would unwind completely with

(bind [1 2]
      (fn [a] (bind [10 100]
                    (fn [b] (bind [-1 1]
                                  (fn [c] (unit (* a b c))))))))

The domonad is just sugar. You can see a very simple implementation at my answer here.

Community
  • 1
  • 1
A. Webb
  • 26,227
  • 1
  • 63
  • 95