(道歉,如果我的術語是錯誤的)。如何指定內聯類型中使用的類型變量,是否與函數定義中使用的類型變量相同?
我想寫處理異常的包裝功能:如果給定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'? – bheklilr
相關解釋在這裏:http://stackoverflow.com/questions/15800878/scoped-type-variables-require-explicit-foralls-why – stusmith