无法将预期类型“a”与实际类型“Double”匹配:

时间:2016-07-19 03:30:22

标签: haskell

我通过从ghci检查它来声明类型声明,但加载模块会出错:

even-fibbanaci-sum.hs:7:12: error:
     Couldn't match expected type ‘a’ with actual type ‘Double’
     ‘a’ is a rigid type variable bound by
       the type signature for:
         getFib :: forall b a. (Integral b, Floating a) => b -> a
       at even-fibbanaci-sum.hs:4:12
     In the expression: ((phi ^ n) - (minusphi ^ n)) / sqrt 5
     In an equation for ‘getFib’:
         getFib n = ((phi ^ n) - (minusphi ^ n)) / sqrt 5    • Relevant bindings include
       getFib :: b -> a (bound at even-fibbanaci-sum.hs:5:1)

这是我的代码

phi = (1 + sqrt 5) / 2
minusphi = (1 - sqrt 5) / 2

getFib ::  (Integral b,Floating a) => b -> a
getFib n = ((phi ^ n) - (minusphi ^ n)) / sqrt 5

fibSum :: (Integral b,Floating a) => b -> a
fibSum x =sum $ map getFib [2,5..x]

但是当它在ghci中它工作正常。

1 个答案:

答案 0 :(得分:7)

这是monomorphism restriction

的示例

当您将文件加载到ghci或使用ghc进行编译时,会启用单态限制,这意味着您会在类型推断中获得某些默认规则。在这种情况下,Haskell推断phiminusphi的类型为Double,而不是Floating a => a,这正是您想要的。

ghci本身中,单态性限制未启用,因此最常见的类型被推断。

要在上面的示例中修复此问题,只需添加显式类型注释:

phi, minusphi :: Floating a => a
phi = (1 + sqrt 5) / 2
minusphi = (1 - sqrt 5) / 2

Here's上一个问题,它有更好的答案IMO。