name
name

Reputation: 362

Is Haskell's Laziness Preserved at Compilation?

So I'm new to this whole functional programming deal. In my recent adventures to learn about Haskell, I've come across a curious question. I'm aware that the GHC interactive environment allows for what is called "lazy" evaluation, which means that Haskell expressions are only evaluated when their values are required. This sounds like a very useful behavior, since it could help simplify the optimization process. My next logical thought went to: then what happens when Haskell is compiled to machine code? Do you lose your laziness? Is it turned into "imperative" code?

Upvotes: 1

Views: 125

Answers (1)

Ingo
Ingo

Reputation: 36329

To be sure, on contemporary hardware Haskell code is ultimately turned into imperative code, namely assembly code, which is imperative.

This does not mean that laziness must vanish, and in fact, it doesn't. Mind you that it is possible to model lazy data structures in imperative languages. For example, one could do the following to model a lazy list of values (note: I am not saying that existing Haskell implementations do it that way, I just want to show how it could be done):

struct List {
    Value *val;
    struct {
        bool evaluated;
        union {
            struct List *list;
            struct List *(*eval)();
        } ptr;
    } next;
};

So, whenever one needs to go to the tail of a list, there may be either an already evaluated pointer to it (next.ptr.list), or just a pointer to a function that computes such a pointer (next.ptr.eval).

Upvotes: 5

Related Questions