Is it possible to turn off lazy evaluation in Haskell?
Is there a specific compiler flag of library to facilitate this?
I wanted to try something new with a old program that I had written a while back, to see if I can improve performance.
As we've discussed, a Haskell program is actually a series of expressions to be evaluated. However, Haskell uses lazy evaluation. It only evaluates the expressions it absolutely needs to in order to produce the program's output.
Haskell uses a special form of evaluation called lazy evaluation. In lazy evaluation, no code is evaluated until it's needed. In the case of longList , none of the values in the list were needed for computation.
Haskell is often described as a lazy language.
Haskell is a lazy language. This means that the evaluation of expressions is delayed until their values are actually needed. The opposite is eager evaluation, which is what most programming languages implement, like C, Java, and Python.
There are a number of ways to turn a lazy thing strict. You can:
seq
or its close relative ($!)
.BangPatterns
.More information here.
You can't turn off laziness, because the I/O system of Haskell depends on it. Without lazy evaluation this program would run into a busy loop without ever outputting anything:
main = forever (putStrLn "Hello!")
This is because forever c
is an infinite program. With lazy evaluation the program is calculated only as far as necessary to run the next instruction. If you turn off laziness, every function becomes strict, including (>>)
, which basically makes the forever
function diverge:
forever c = let cs = c >> cs in cs
However, you can add strictness annotations to constructors and patterns. When a function is strict, its argument is forced as part of the evaluation of the result independent of whether the argument is needed or not. This resembles eager evaluation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With