What are Haskell's strictness points?

前端 未结 8 1086
伪装坚强ぢ
伪装坚强ぢ 2021-01-29 22:00

We all know (or should know) that Haskell is lazy by default. Nothing is evaluated until it must be evaluated. So when must something be evaluated? There are points where Haskel

8条回答
  •  北荒
    北荒 (楼主)
    2021-01-29 22:41

    The Glasgow Haskell compiler translates your code into a Lambda-calculus-like language called core. In this language, something is going to be evaluated, whenever you pattern match it by a case-statement. Thus if a function is called, the outermost constructor and only it (if there are no forced fields) is going to be evaluated. Anything else is canned in a thunk. (Thunks are introduced by let bindings).

    Of course this is not exactly what happens in the real language. The compiler convert Haskell into Core in a very sophisticated way, making as many things as possibly lazy and anything that is always needed lazy. Additionally, there are unboxed values and tuples that are always strict.

    If you try to evaluate a function by hand, you can basically think:

    • Try to evaluate the outermost constructor of the return.
    • If anything else is needed to get the result (but only if it's really needed) is also going to be evaluated. The order doesn't matters.
    • In case of IO you have to evaluate the results of all statements from the first to the last in that. This is a bit more complicated, since the IO monad does some tricks to force evaluation in a specific order.

提交回复
热议问题