我正在尝试使用类型系统来确保永远不会从 monad M 中取出 X。我希望它的工作方式类似于 runST
,其中不可能混合来自不同线程的环境。
data X s = X Int
type M s = State Int
newX :: M s (X s)
newX = X <$> get
eval :: (forall s. M s a) -> a
eval x = evalState x 0
但是,以下代码不会导致类型错误:
ghci> x = eval newX
ghci> :t x
x :: X s
为什么 ST monad 中的类似代码会抛出错误而我的不会?据我了解
s
在 M s a
应该成为约束,使 s
在 X s
一个自由类型变量,从而导致类型检查器出错。
最佳答案
要强制执行类型抽象,您必须使用 data
或 newtype
,而不是 type
.type
中未使用的参数同义词根本没有效果:
type M s = State Int
所以这些是等价的:
newX :: M s (X s)
newX :: State Int (X s)
eval :: (forall s. M s a) -> a
eval :: State Int a -> a
eval
实际上不是更高级别的。
关于haskell - ST类封装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60058614/