I'm using singletons library. I have this data type:
import Control.DeepSeq
import Data.Singletons.Prelude
import Data.Singletons.TH
data T =
A
| B [T]
genSingletons [''T]
I want generated singleton type ST to be instance of NFData.
It would be straightforward if type T wouldn't be recursive.
I tried to write this:
instance NFData (ST a) where
rnf SA = ()
rnf (SB (x `SCons` xs)) = rnf x `seq` rnf xs
but this fails on last line with message:
Could not deduce (NFData (Sing n1)) arising from a use of `rnf'
from the context (a ~ 'B n)
bound by a pattern with constructor
SB :: forall (z_azEs :: T) (n_azEt :: [T]).
(z_azEs ~ 'B n_azEt) =>
Sing n_azEt -> Sing z_azEs,
in an equation for `rnf'
or from (n ~ (n0 : n1))
bound by a pattern with constructor
SCons :: forall (a0 :: BOX) (z0 :: [a0]) (n0 :: a0) (n1 :: [a0]).
(z0 ~ (n0 : n1)) =>
Sing n0 -> Sing n1 -> Sing z0,
in an equation for `rnf'
In the second argument of `seq', namely `rnf xs'
In the expression: rnf x `seq` rnf xs
In an equation for `rnf':
rnf (SB (x `SCons` xs)) = rnf x `seq` rnf xs
I understand that GHC wants x and xs in pattern SB (x ``SCons`` xs)) to be instances of NFData, but I have trouble figuring out how exactly to tell this.
What should I write in the context of this instance to make it work?
First, you need to provide NFData instances for singleton lists.
instance NFData (SList '[]) where
rnf SNil = ()
instance (NFData (Sing x), NFData (SList xs)) => NFData (SList (x ': xs)) where
rnf (SCons x xs) = rnf x `seq` rnf xs
Note that you can't solve this in a single instance, because that way you couldn't provide the recursive NFData constraints:
instance NFData (SList xs) where
rnf SNil = ()
rnf (SCons x xs) = ? -- no way to know if NFData (Sing x)
Similarly, you have to write separate instances for the T cases:
instance NFData (ST A) where
rnf SA = ()
instance NFData (SList xs) => NFData (ST (B xs)) where
rnf (SB xs) = rnf xs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With