Hacker News new | ask | show | jobs
by wyager 4384 days ago
>lazy evaluation is one of those features where i have absolutely no idea what benefit it actually provides

Good question.

Let's say you have a program like this little python example:

    inputs = [raw_read() for i in range(1000)] # Read numbers from command line
    numbers = map(int, inputs) # Turn them into integers
    for num in numbers: # Check for 42
      if num == 42:
        return true
    return false # It's not there
If you use lazy evaluation, each item in the "map" object will only be calculated as needed. So if the first item in the "inputs" list is "42", it will only do a single string-to-integer conversion.

If you use greedy evaluation, it will map all strings to integers at once, which might be wasteful.

There are other benefits as well; this is the most obvious.

1 comments

But in a language with mutating side effects, and iterators, I'm not sure what this buys you over:

    for (auto& num = file.line_iterator(); num != file.end(); num++) {
        if (atoi(num) == 42)
            return true;
    return false;
Note that 'line_iterator()' isn't something that (as far as I know) is defined in the C++ standard library, but there's nothing preventing it.
Compare the code you wrote with what I wrote.

Lazy evaluation gets you all that, with no extra code, all the time.

Imagine writing that iterator stuff for every single applicable thing in the entire program. There are also other places where lazy evaluation is useful and you can't use iterators, like a function that will only use a portion of its arguments depending on some condition.

> But in a language with mutating side effects, and iterators, I'm not sure what this buys you...

Side-effect free, functional style of programming.