Hi all
I have seen lexi-lambda’s part 4 video on laziness. On there, there is a safeDiv
function that was not optimized as much as it could because it returned a Maybe Double
. The demand structure was hidden inside the Just
constructor.
So the author goes on to establish some rules. She does not really want to hide some computations in constructors, but given lazy binding in data types, that is what she gets by default. On the previous videos she made the point that non-strict semantics are pretty great for code optimization. They let the compiler move stuff around in a semantics preserving way. But it does need a good demand structure for it to work well. More thunks being the result of the demand structure not being clear enough, instead of just when the computation actually had to be suspended.
So she establishes some guides:
- Function should be lazy, so the demand structure is just the data dependencies
- But most data type types (tuples, either, maybe) could be WHNF strict on the values (as with strictData)
- Except on the case they are recursive (List, Seq, Map), in which case you need to do a case by case analysis. List and Seq should be lazy. Map needs to be at least spine strict.
I have been playing with this style and it is pretty great. Long lived data structures become “sync points” as she calls them. They are either completely suspended or completely forced. You can use strict-wrapper to convert between representations with ease. The produced STG is great
But what do we lose? Well:
- It seems that functor instances given that undefined it is a value.. Also, no state monad is possible for the strict tuple for the same reason. Same with MonadFix
- Fixed points for records where values depend on previously set fields.
But you keep:
- Lazy
let
andwhere
bindings on function bodies - Lazy list as streams
- Higher order functions for code reuse
So I want to hear more opinions on this programming style. I would go as far as to propose to including strict versions of Maybe
, Tuple
and Either
on base. What has been your experience? Completely against? let me hear what you think!