Imperative parallels to Haskell's Monad operations
https://softwareengineering.stackexchange.com/questions/410978
-
12-03-2021 - |
Pregunta
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.,
operatordo
expressions ~ C/C++/JavaScript/etc.;
operator (kinda)MonadFail
'sfail
~ 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);
Solución
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.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a softwareengineering.stackexchange