Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is that not lazy

Tags:

haskell

ghc

I'm still starting to explore Haskell. I know this code "runs" in the IO monad. When it goes from the l <- ... line to the next one, the IO - bind is called.

One could think that because Haskell is lazy, the l is never evaluated. But "bind" always evaluates the previous command, is that right? Because the program produces the "file-not-found" error.

main = do
    l <- mapM readFile [ "/tmp/notfound" ]
    return ()
like image 481
Cartesius00 Avatar asked Dec 01 '12 20:12

Cartesius00


People also ask

Is lazy a real thing?

Laziness (also known as indolence) is disinclination to activity or exertion despite having the ability to act or to exert oneself. It is often used as a pejorative; terms for a person seen to be lazy include "couch potato", "slacker", and "bludger".

What causes being lazy?

Lifestyle causes of laziness For example, a poor diet, too much alcohol and lack of good quality sleep can all leave you feeling tired and unmotivated. Stress can also lead to poor sleep, which in turn can make you feel tired and lacking motivation.

Is it possible to not be lazy?

Taking small steps toward better self-care, increased energy, improved goals, and healthy boundary setting can help you stop feeling lazy in no time. Prioritizing and taking consistent action steps are the key to long-term change and there is no better time than now to take those first steps.

Why is procrastination not lazy?

Procrastination and laziness are two different concepts: procrastination involves delaying unnecessarily, whereas laziness involves being voluntarily unwilling to exert necessary effort.


2 Answers

One could think that because Haskell is lazy, the l is never evaluated.

Yes, and it never is evaluated. However, due to the definition of (>>=) in IO, the action readFile "/tmp/notfound" is executed, and that means the runtime tries to open the file. If there is no such file, a "File not found" error is raised. If there were such a file, it would be opened, but its contents would not be read until demanded. In the above, they are not demanded, so the contents will not be read.

What is evaluated here (and even executed) is the action producing l. Since the file doesn't exist, that raises an error.

like image 97
Daniel Fischer Avatar answered Sep 21 '22 23:09

Daniel Fischer


If you expand the do notation in your code, you get:

main = (mapM readFile ["/tmp/notfound"]) >>= (\l -> return ())

So yes, l is never evaluated, but that doesn't mean that the call to mapM is never evaluated. >>= always needs to evaluate its left operand in order to produce a value at least to some degree (at least in the IO monad and in any other monad that comes to mind).

like image 43
sepp2k Avatar answered Sep 21 '22 23:09

sepp2k