27 ms·
It's worth noting that while monads themselves naively introduce a data dependency, that doesn't necessarily force evaluation order. If the compiler is smart en
by zenhack 9y ago
It's worth noting that while monads themselves naively introduce a data dependency, that doesn't necessarily force evaluation order. If the compiler is smart enough and sees something like:
foo >>= \_ -> bar
It is well within its rights to evaluate bar and then foo, or do both in parallel, or not evaluate foo at all, as long as it can guarantee that the resulting value is the same. The big thing it needs to be careful of is not to introduce nontermination.
What makes this do the right thing for effects is what values of type IO actually are, and what bind means specifically for IO. It's helpful to think of an IO value as code in another (imperative) language. Bind takes two fragments of code in that other language, and stitches them together into a script that executes one after the other.
The key thing is that the order in which you compute parts of the script is entirely orthogonal to the order the commands appear in the script.
In Haskell, evaluation does not cause side effects, period. `main` is a value of type IO, which is executed when the program is run. The effects of that execution are independent of how the value `main` is computed.
Obviously, the computation itself takes time and space though.