假设我们有一个类似 f 的函数,它返回一个 monad。然而,在你看到的地方Int
,假装它是一个非常复杂的类型。
f :: (Monad m) => m Int -- Pretend this isn't Int but something complicated
f = return 42
现在让我们说我们想强制它进入Maybe
monad。我们不需要编写完整的类型f
来执行此操作,我们可以执行以下操作:
g :: Maybe a -> Maybe a
g = id
main = print $ (g f)
哑函数g
强制f
变为Maybe
。
我认为上面的内容相当混乱。我宁愿写的是这样的:
main = print $ (f :: Maybe a)
但它失败并出现以下错误:
Couldn't match expected type `a' against inferred type `Int'
`a' is a rigid type variable bound by
the polymorphic type `forall a. Maybe a' at prog.hs:7:16
Expected type: Maybe a
Inferred type: Maybe Int
In the second argument of `($)', namely `(f :: Maybe a)'
In the expression: print $ (f :: Maybe a)
有没有办法以g
不涉及创建新功能的不那么混乱的方式完成上述工作?我不想写f :: Maybe Int
,因为如果返回类型发生变化,它就会成为维护问题。GHC 扩展在答案中是可以的。