相关疑难解决方法(0)

不完整的类型签名

让我们说我们有一个像f这样的函数,返回一个monad.但是,你看Int,假装它是一个非常复杂的类型.

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

现在让我们说我们想强迫它进入Maybemonad.我们不需要编写完整类型f来执行此操作,我们可以执行以下操作:

g :: Maybe a -> Maybe a
g = id

main = print $ (g f)
Run Code Online (Sandbox Code Playgroud)

虚拟函数g强制f成为Maybe.

我认为上面的内容相当混乱.我宁愿写的是这样的:

main = print $ (f :: Maybe a)
Run Code Online (Sandbox Code Playgroud)

但它失败并出现以下错误:

Couldn't match expected type `a' against inferred type `Int'
  `a' is a rigid type variable bound by
      the polymorphic type …
Run Code Online (Sandbox Code Playgroud)

haskell type-inference ghc

7
推荐指数
2
解决办法
325
查看次数

标签 统计

ghc ×1

haskell ×1

type-inference ×1