haskell / deepseq

Deep evaluation of data structures
http://hackage.haskell.org/package/deepseq
Other
40 stars 29 forks source link

Add method to help with strict containers #97

Open treeowl opened 1 year ago

treeowl commented 1 year ago

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 commented 1 year ago

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

TeofilC commented 6 months ago

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.