6

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

Will Ness
  • 70,110
  • 9
  • 98
  • 181
Matthew Leon
  • 123
  • 3
  • 1
    Note that as was somewhat discussed in that linked possible duplicate, the distinction between what is considered WHNF and what is considered something that will certainly, in a short time and without side effects evaluate *into* WHNF is a somewhat arbitrary decision. – Ørjan Johansen Aug 31 '14 at 22:31

1 Answers1

9

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).

leftaroundabout
  • 117,950
  • 5
  • 174
  • 319
  • Even `\x -> (1 + 1 :: Integer)`? – user253751 Nov 03 '16 at 03:54
  • It seems like `(1 + 1 :: Integer)` could be reduced to `2 :: Integer` before the lambda is called – user253751 Nov 03 '16 at 21:09
  • Well, yes, but that would be a matter of optimisation. Most definitely, `\x -> 1 + undefined` does not try to evaluate the result unless you call the function. I.e. _semantically_, a lambda is always already in NF. – leftaroundabout Nov 03 '16 at 21:16