2

I declared the type declaration by checking it from ghci but loading the module gives error:

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)

Here is my code

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]

but when it in ghci it works fine.

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
user3125971
  • 139
  • 3
  • 15

1 Answers1

7

This is an example of the monomorphism restriction.

When you load a file into ghci or compile it with ghc, the monomorphism restriction is enabled, which means that you get certain defaulting rules in type inference. In this case, Haskell infers that phi and minusphi have type Double instead of Floating a => a, which is what you wanted.

In ghci itself though, the monomorphism restriction is not enabled, so the most general types are inferred.

To fix this in your example above, just add the explicit type annotation:

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

Here's a previous question which has a better answer IMO.

Community
  • 1
  • 1
Alec
  • 31,829
  • 7
  • 67
  • 114