30

In the chain documentation you find:

Calling chain on a wrapped object will cause all future method calls to return wrapped objects as well. When you've finished the computation, use value to retrieve the final value.

So does the chain function create a monad?

user3335966
  • 2,673
  • 4
  • 30
  • 33
jcubic
  • 61,973
  • 54
  • 229
  • 402

1 Answers1

39

No, not a monad, but a comonad! It turns a function that takes a wrapped object and returns a normal value into a function that both takes and returns a wrapped object. As a Haskell type signature that would be:

(Wrapped a -> b) -> (Wrapped a -> Wrapped b)

The type signature of value is:

Wrapped a -> a

These are precisely what you need for a comonad. The first function is usually called extend and the second extract.

You can think of a comonad as a value with some extra context. And that is of course exactly what chain does.

See this Stackoverflow question for more about comonads.

Community
  • 1
  • 1
Sjoerd Visscher
  • 11,840
  • 2
  • 47
  • 59
  • 9
    I like this answer; I think it would be more immediately apparent what you mean if you were to explain the mapping of underscore object methods onto types. If I understand correctly, methods are normally `Wrapped a -> b`s but that `chain` returns an object whose methods (except `value`) are all `Wrapped a -> Wrapped b`s. I know a little Haskell, but the question was not originally tagged Haskell so explanations of how your answer maps to the JS library might be helpful. – ellisbben May 04 '12 at 15:21
  • I have a similar comment here: I understand chain as a function that takes a value and returns a wrapped object so `chain:: a => Wrapped a`, and that makes it look like a monadic `return` or `unit`. Methods used on `Wrapped` are such that `method:: Wrapped a -> (a -> b) -> Wrapped b`. For instance, map or reduce (`_ -> f -> reduce(_, f, seed)`). That looks like standard `method _ f = fmap f _` with a different f for each method. Except the `value` method which is `:: Wrapped a -> a` and indeed looks like a comonadic `extract`. There could be a comonad involved but it is not easily visible. – user3743222 May 29 '20 at 17:23