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?

1
  • 3
    I've tagged this haskell, because haskellers might have something to say on this topic.
    – Marcin
    May 4, 2012 at 13:59

1 Answer 1

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.

2
  • 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 -> bs but that chain returns an object whose methods (except value) are all Wrapped a -> Wrapped bs. 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 4, 2012 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. May 29, 2020 at 17:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.