0

Would it be (mostly) correct to say that the following are the parallels to the Haskell Monad operations in the imperative world?

  • Monad's >> ~ C/C++/JavaScript/etc. , operator
  • do expressions ~ C/C++/JavaScript/etc. ; operator (kinda)
  • MonadFail's fail ~ C/C++/JavaScript/etc. throw

To demonstrate the point, some examples:

Sequentially evaluate, but discard first result:

Haskell:

a = doSomething >> doSomethingElse

C++:

auto a = (doSomething(), doSomethingElse());

JavaScript:

const a = (doSomething(), doSomethingElse());

Evaluate one after the other, reusing previous results:

Haskell:

do a <- doSomething
   doSomethingWith a

JavaScript:

const a = doSomething();
doSomethingWith(a);
7
  • For C++ the equivalent is std::optional, can't tell for Java or C. Jun 2, 2020 at 19:40
  • @πάνταῥεῖ You're thinking about Maybe, but it's not the only Monad... I was thinking more about Monad in general
    – P Varga
    Jun 2, 2020 at 19:41
  • std::optionals can be easily chained. Jun 2, 2020 at 19:54
  • I know, this isn't about std::optional though, it's about Monad
    – P Varga
    Jun 2, 2020 at 20:05
  • Haskell doesn't really have doSomething. It's all someValue, so >> is only relevant in composing effects. do notation generalises language and library features like foreach, async, if error goto fail, logging etc.
    – Caleth
    Jun 2, 2020 at 21:57

1 Answer 1

5

If it helps you wrap your head around it, your intuition is a decent analogy for some monads. Consider, however, the list monad:

Prelude> [1, 2, 3] >> [4, 5, 6]
[4,5,6,4,5,6,4,5,6]
Prelude> [1, 2, 3] >>= \x -> map (*x) [4, 5, 6]
[4,5,6,8,10,12,12,15,18]
-- Doesn't even have a fail

Monads are a much more abstract concept than most imperative programmers are accustomed to dealing with. It's okay to start on the path to understanding them by focusing on a few specific monads, but long term don't make your understanding of them too narrow.

Your Answer

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

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