I'm have been using Haskell for a while and I'm having some trouble with Numeric Types. Most of the time I can solve the after trying around a bit but this time i have been stumped for over two hours by this trivial piece of code.
I have these Functions:
takeLessEqual x = takeWhile (<=x)
leftHalf x = takeLessEqual x $ (map (\x -> ((x+0.5)*(x+0.5) + 0.75))) [1..]
-- Produces the list [3.0,7.0,13.0,21.0,31.0,43.0 ... (some number < x)]
rightHalf x = takeLessEqual x $ (map (\x -> if even x then x*x + 1 else x*x)) [1..]
-- Produces the list [1,5,9,17,25,37,49 ... (some number < x)]
total x = (sum $ rightHalf x) + (sum $ leftHalf x)
-- total 10 Should produce some number 25 or 25.0
It loads without error in to ghci, but when i try to evaluate:
*> leftHalf 10
[3.0,7.0]
it :: (Ord a, Fractional a, Enum a) => [a]
*> rightHalf 10
[1,5,9]
it :: Integral a => [a]
*> total 10
<interactive>:150:1: error:
• Ambiguous type variable ‘a0’ arising from a use of ‘it’
prevents the constraint ‘(Fractional a0)’ from being solved.
Probable fix: use a type annotation to specify what ‘a0’ should be.
These potential instances exist:
instance Fractional Double -- Defined in ‘GHC.Float’
instance Fractional Float -- Defined in ‘GHC.Float’
...plus one instance involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the first argument of ‘print’, namely ‘it’
In a stmt of an interactive GHCi command: print it
And I have tried adding type annotations at various points and converting types with toInteger and fromIntegral with no success.
What am I doing wrong and how do I fix it?
total 10 :: DoubleIntegralandFractionalat the same time, but yourtotalfunctions needs such a type!leftHalfasleftHalf x = takeLessEqual x $ map (\x -> (x * x + x + 1) [1..]and it'll work for all numeric types, not justIntegralorFractionaltypes.