我通过从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)
Run Code Online (Sandbox Code Playgroud)
这是我的代码
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]
Run Code Online (Sandbox Code Playgroud)
但当它在ghci它工作正常.
这是单形态限制的一个例子.
当您将文件加载ghci或编译时ghc,启用单态限制,这意味着您在类型推断中获得某些默认规则.在这种情况下,Haskell推断出phi并且minusphi有类型Double而不是Floating a => a,这是你想要的.
在ghci本身虽然,单态限制未启用,所以最普通类型的推断.
要在上面的示例中修复此问题,只需添加显式类型注释:
phi, minusphi :: Floating a => a
phi = (1 + sqrt 5) / 2
minusphi = (1 - sqrt 5) / 2
Run Code Online (Sandbox Code Playgroud)