gpt4 book ai didi

haskell - 如何为递归单例类型定义 NFData 实例?

转载 作者:行者123 更新时间:2023-12-02 21:19:39 24 4
gpt4 key购买 nike

我正在使用singletons库。我有这个数据类型:

import Control.DeepSeq
import Data.Singletons.Prelude
import Data.Singletons.TH

data T =
A
| B [T]

genSingletons [''T]

我希望生成的单例类型 ST 成为 NFData 的实例。如果类型 T 不是递归的,那就很简单了。我尝试这样写:

instance NFData (ST a) where
rnf SA = ()
rnf (SB (x `SCons` xs)) = rnf x `seq` rnf xs

但是最后一行失败并显示消息:

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

据我了解,GHC 希望模式 SB (x ``SCons`` xs)) 中的 xxs 成为 的实例code>NFData,但我很难弄清楚如何准确地讲述这一点。我应该在此实例的上下文中编写什么才能使其正常工作?

最佳答案

首先,您需要为单例列表提供 NFData 实例。

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

请注意,您无法在单个实例中解决此问题,因为这样您就无法提供递归 NFData 约束:

instance NFData (SList xs) where
rnf SNil = ()
rnf (SCons x xs) = ? -- no way to know if NFData (Sing x)

同样,您必须为 T 情况编写单独的实例:

instance NFData (ST A) where
rnf SA = ()

instance NFData (SList xs) => NFData (ST (B xs)) where
rnf (SB xs) = rnf xs

关于haskell - 如何为递归单例类型定义 NFData 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31477176/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com