Are continuations monads?

2019-03-11 02:58发布

问题:

Can continuations be said to be monads? Are they a subset of monads or are they simply a way of implementing monads?

Edit: Or maybe I got it wrong and monads is a more abstract concept than continuations? (So I'm really comparing apples to oranges here)

回答1:

Briefly, since the 'bind' of a monad takes an effective continuation (a lambda of the 'rest of the computation') as an argument, monads are continuations in that sense. On the flip side, continuation-passing style can be effectively implemented in a non-CPS language using monadic syntax sugars, as suggested by a number of misc links below.

From the 'all about monads' tutorial in Haskell:

https://www.haskell.org/haskellwiki/All_About_Monads#The_Continuation_monad

An F# continuation monad, used to implement 'break' and 'continue' for for-style-loops

http://cs.hubfs.net/forums/thread/9311.aspx

And example of applying a continuation monad to a problem in F#:

http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!256.entry



回答2:

Not only are continuations monads, but they are a sort of universal monad, in the sense that if you have continuations and state, you can simulate any functional monad. This impressive but highly technical result comes from the impressive and highly technical mind of Andrzej Filinski, who wrote in 1994 or thereabouts:

We show that any monad whose unit and extension operations are expressible as purely functional terms can be embedded in a call-by-value language with “composable continuations”.



回答3:

They can be, although they don't need to be. I'd reverse your question a little bit and say instead that monads are a way of implementing continuations. But you can implement continuations in many ways -- you can do a modest but constrained facsimile of CPS in C# without too much effort, for example. Have a look at The Continuation Monad from the Haskell site for a very thorough treatment.



回答4:

A very nice article on that topic: http://blog.sigfpe.com/2008/12/mother-of-all-monads.html



回答5:

A continuation is a particular function in a program. Monads are type constructors.

A type constructor Cont<T> for continuations taking type T would not be a monad.

However, Cont<Cont<T>> is a monad, and this is what is commonly called "the continuation monad".

(Having callcc in a language is equivalent to being able to convert from Cont<Cont<T>> to T.)