Search code examples
functional-programminglazy-evaluationthunk

When is it better to thunk?


When is it better to use lazy evaluation instead of the eager one? Is it better when you know that the expression will be computed only once or maybe never?


Solution

  • If you have the choice, use lazy evaluation for expressions that may not be evaluated at all or may lead to programming errors under certain circumstances when evaluated.

    The classic case is implemented in most languages descending from C and is called "short circuit operators":

    if (i != 0 && n/i > 100) ...
    

    Here, n/i > 100 will only be computed when i is not 0. Which is nice, since it avoids a zero divide error.