不完整的类型签名

时间:2012-08-01 01:19:28

标签: haskell ghc type-inference

让我们说我们有一个像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扩展在答案中是可以接受的。

2 个答案:

答案 0 :(得分:10)

使用asTypeOf。它返回第一个参数,同时将其类型与第二个参数统一。它只是const的类型限制版本,但对于这种情况很有用。

main = print $ f `asTypeOf` (undefined :: Maybe a)

答案 1 :(得分:8)

另一种方法是限制print的类型:

main = (print :: Show a => Maybe a -> IO ()) f