Search code examples
haskellweak-head-normal-form

Why does Haskell consider lambda abstractions to be in Weak Head Normal Form (WHNF)?


In Haskell, lambdas are considered to be in WHNF, while unapplied user-defined functions are not. What was the motivation behind this distinction?


Solution

  • It's often useful to attach information to a function that needs to be calculated before you can ever evaluate the function, but that can afterwards be shared across invocations.

    cleverFunction = \x -> simpleCombine x expensiveConstant
     where expensiveConstant = ...
           simpleCombine x c = ...
    

    Note that though cleverFunction is defined as a lambda, it is not in WHNF because of the where block (sugar for (\l x -> ...) locBindings).

    A lambda without any enclosing scope has no variables that could be calculated before invocation (variables in the lambda are only valid for a single call, and garbage-collected afterwards), i.e. it is already in normal form (actually NF, not just WHNF).