How the sequel monad really works

I understand how Reader or Maybe or state monads work, but havig hard times with Continuations monad. Examples, as shown below, are a header.

type ContinuationMonad() =
   member this.Bind (m, f) = fun c -> m (fun a -> f a c)
   member this.Return x = fun k -> k x

I think my problem is that I cannot get what is a monadic type to continue with (for example, Cont <'T>), and how can I expand it and wrap it back. Any useful examples or links are highly appreciated.

+4
source share
2 answers

, - . , , - Cont<'T>:

type Cont<'T> = 
  Cont of (('T -> unit) -> unit)

Cont<'T> . , 'T -> unit, - (, ). , unit, ( - ) 'T , .

:

type ContinuationMonad() =
   member this.Bind (ma, f) = 
      Cont(fun k -> 
        let (Cont ca) = ma
        ca (fun a -> 
            let (Cont cb) = f a
            cb k))

   member this.Return x = 
      Cont(fun k -> k x)
  • Return , k x, .

  • Bind , k , m; a, f, , f, k ( "" , ).

+10

, :

  • Cont IMHO (), a Cont . Inc, "" . ( 'T), . : Inc - , .

  • Inc . Bind.

  • , , unit, , .

, 'T -> unit, Inc :

type Inc<'T> = 
    ('T -> unit) -> unit

Inc 'T , unit.

Bind. , , :

let bind (inc : Inc<'T>) (wrap : 'T -> Inc<'U>) : Inc<'U> =

, Bind ( 'T) , "" ( 'U) , , , Bind Inc, Inc - , . , Bind :

    fun (cont : 'U -> unit) -> ...

- 'T, Inc, -. . - Inc , ! "" . Bind :

let bind (inc : Inc<'T>) (wrap : 'T -> Inc<'U>) : Inc<'U> =
    fun (cont : 'U -> unit) ->   // return an Inc, which is a function that takes a continuation as input
        inc (fun t ->            // force the incomplete computation to cough up its wrapped value
            (wrap t) cont)       // wrap the raw value so it can be sent to the given continuation
+1

Source: https://habr.com/ru/post/1657818/


All Articles