I am trying to make a simple code to get an aproximation for PI using haskell. However it seems the program predicts the result of the division is an Integer, even though the division is never exact (again, it is PI).... Or at least that is what I understand :P
Here is the code:
divpi :: Integer -> Double
divpi k = (((fatc (6*k)) * ((545140134*k) + 13591409))/((fatc (3*k)) * (pot (fatc k) 3) * (pot (-262537412640768000) k)))
fatc is factorial (fatc number) and pot is integer exponentiation (pot base exponent)
The error message:
ERROR file:.\haskel.hs:33 - Type error in explicitly typed binding
*** Term : divpi
*** Type : Integer -> Integer
*** Does not match : Integer -> Double
If necessary, here is the entire code
答案 0 :(得分:1)
In Haskell, /
works on Fractional
types. Yet your fatc
and pot
return integers. Haskell, unlike C, will never implicitly convert between any types, so we need to use fromInteger
to get non-integer values out of it.
divpi :: Integer -> Double
divpi k = (fromInteger ((fatc (6*k)) * ((545140134*k) + 13591409)) / fromInteger ((fatc (3*k)) * (pot (fatc k) 3) * (pot (-262537412640768000) k)))
Also, as a future note, when you have complicated arithmetic like this, consider using where
and let
to create some intermediate variables. In addition to making things more readable, you'll get better error messages as well.