Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

turn off lazy evaluation in haskell

Tags:

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.

like image 810
pyCthon Avatar asked Mar 26 '13 01:03

pyCthon


People also ask

Does Haskell use lazy evaluation?

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.

Does Haskell support lazy processing?

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.

Is Haskell lazy or eager?

Haskell is often described as a lazy language.

What does it mean that Haskell is lazy?

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.


2 Answers

There are a number of ways to turn a lazy thing strict. You can:

  1. Explicitly insert a spurious pattern match.
  2. Use seq or its close relative ($!).
  3. Use BangPatterns.
  4. Use strictness annotations on your types.

More information here.

like image 148
Daniel Wagner Avatar answered Sep 28 '22 01:09

Daniel Wagner


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.

like image 39
ertes Avatar answered Sep 28 '22 03:09

ertes