我写了以下函数:

(.>=.) :: Num a => STRef s a -> a -> Bool
r .>=. x = runST $ do
 v <- readSTRef r
 return $ v >= x

但是当我尝试编译时,出现以下错误:
Could not deduce (s ~ s1)
from the context (Num a)
  bound by the type signature for
             .>=. :: Num a => STRef s a -> a -> Bool
  at test.hs:(27,1)-(29,16)
  `s' is a rigid type variable bound by
      the type signature for .>=. :: Num a => STRef s a -> a -> Bool
      at test.hs:27:1
  `s1' is a rigid type variable bound by
       a type expected by the context: ST s1 Bool at test.hs:27:12
Expected type: STRef s1 a
  Actual type: STRef s a
In the first argument of `readSTRef', namely `r'
In a stmt of a 'do' expression: v <- readSTRef r

有人可以帮忙吗?

最佳答案

这完全符合预期。 STRef仅在runST的一次运行中有效。然后您尝试将外部STRef放入新的runST中。那是无效的。那将在纯代码中产生任意副作用。

因此,您无法尝试实现的目标。通过设计!

关于variables - GHC是否拒绝ST monad代码无法统一类型​​变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8007076/

10-13 09:46