【发布时间】:2014-06-24 20:42:06
【问题描述】:
(抱歉,如果我的术语有误)。
我正在尝试编写一个处理异常的包装函数:如果给定的IO 动作抛出,它返回Nothing(当然在IO 上下文中),但如果给定的IO 动作成功,它返回Just v。
tryMaybe :: IO a -> IO (Maybe a)
tryMaybe action = do
result <- (try action) :: IO (Either SomeException a)
return $ case result of
Left _ -> Nothing
Right v -> Just v
这会导致编译器错误消息:
Couldn't match type `a' with `a1'
`a' is a rigid type variable bound by
the type signature for tryMaybe :: IO a -> IO (Maybe a)
at src/Database.hs:33:13
`a1' is a rigid type variable bound by
an expression type signature: IO (Either SomeException a1)
at src/Database.hs:35:15
Expected type: IO a1
Actual type: IO a
In the first argument of `try', namely `action'
我猜第一行中的类型变量a 与第三行中的a 不同——它们恰好在源代码中具有相同的名称,并且编译器具有在错误消息中将其重命名为a1。
那么我如何告诉 Haskell 这些是相同的类型呢?
【问题讨论】:
-
你试过
ScopedTypeVariables吗?
标签: haskell type-inference type-variables