不完整的类型签名

假设我们有一个如下面的函数f,返回一个单子。 然而,在你看到Int ,假装它是一个非常复杂的类型。

f :: (Monad m) => m Int -- Pretend this isn't Int but something complicated
f = return 42

现在让我们说我们想强制这个成Maybe单子。 我们不需要编写完整的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扩展在答案中没有问题。


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

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

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

main = (print :: Show a => Maybe a -> IO ()) f
链接地址: http://www.djcxy.com/p/1145.html

上一篇: Incomplete type signature

下一篇: Haskell: What is Weak Head Normal Form?