GHC拒绝ST monad代码无法统一类型​​变量?

时间:2011-11-04 09:21:02

标签: variables haskell types ghc unification

我写了以下函数:

(.>=.) :: 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

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:12)

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

所以,你尝试的是不可能实现的。按设计!

答案 1 :(得分:7)

您需要保持在ST范围内:

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

(正如hammar指出的那样,要使用>=,您需要Ord类型类Num未提供的类型类。)