deepseq icon indicating copy to clipboard operation
deepseq copied to clipboard

Add method to help with strict containers

Open treeowl opened this issue 2 years ago • 2 comments

I propose an NFData method (by some name)

  whnfIsNf :: proxy a -> Bool
  whnfIsNf _ = False

Then we can have, for example,

instance NFData Integer where
  whnfIsNf _ = True
instance NFData a => NFData (Set a) where
  whnfIsNf _ = whnfIsNf (Proxy :: Proxy a)
  rnf
    | whnfIsNf (Proxy :: Proxy a)
    = \ !_ -> ()
    | otherwise
    = ....

This can avoid a bunch of unnecessary traversals.

treeowl avatar Apr 03 '23 23:04 treeowl

We could also offer a function to derive this for Generic instances without the risk of going out of date if the type changes.

treeowl avatar Apr 04 '23 00:04 treeowl

You might find my th-deepstrict library helpful https://tracsis.github.io/th-deepstrict/

It uses TH to allow making the whnf is nf assertion you mention, which the library calls deep strictness.

In terms of Generics, @bgamari wrote up some code a while ago that does something like this, and I modified it to work with (mutual) recursive types (the trick is you have to treat this as an inductive proof): https://gist.github.com/TeofilC/a85da6a388ec94e8acb1519886fbd2a7 See some earlier discussion here: https://github.com/haskell/deepseq/issues/3

In the end, the trickiness of doing this with Generics led me towards TH.

TeofilC avatar Feb 14 '24 11:02 TeofilC