Reputation: 27
I have a problem with defining the type of a function. In the cases of 1, 10, 11 and 12, I insert an Int and return a float, but in the case in which I insert an Int and return an Int the types doesn't match. I tried with pointsForSeventy:: Int->Float and also with pointsForSeventy:: Real a-> Int->a (I thought this one would work because Integrals and Fractionals are inside the Real numbers)
pointsForSeventy 1 = 5.5
pointsForSeventy 10 = 0.5
pointsForSeventy 11 = 0.5
pointsForSeventy 12 = 0.5
pointsForSeventy a = a
Thanks in advance
Upvotes: 0
Views: 1778
Reputation: 116174
You need an explicit conversion:
pointsForSeventy 1 = 5.5
pointsForSeventy 10 = 0.5
pointsForSeventy 11 = 0.5
pointsForSeventy 12 = 0.5
pointsForSeventy a = fromIntegral a
Unlike several other programming languages, Haskell will never automatically perform automatic or implicit conversion between numeric types.
On the other hand, numeric literals belong to any numeric type. E.g. 1/2*0.5 :: Double
will return 0.25
since all the three literals are Double
s. In some languages like C, instead, 1/2*0.5
evaluates to 0
since 1/2
is integer division (!), and evaluates to 0
.
Upvotes: 3
Reputation: 477170
Haskell is a statically typed language. So that means that the return type can not depend on the value of the input.
An idea might be to convert the Int
into a Float
by using fromIntegral :: (Integral a, Num b) => a -> b
:
pointsForSeventy :: Int -> Float
pointsForSeventy 1 = 5.5
pointsForSeventy 10 = 0.5
pointsForSeventy 11 = 0.5
pointsForSeventy 12 = 0.5
pointsForSeventy a = fromIntegral a
In case you want to treat the Int
case different from the Float
case, you can also use Either
:
pointsForSeventy :: Int -> Either Float Int
pointsForSeventy 1 = Left 5.5
pointsForSeventy 10 = Left 0.5
pointsForSeventy 11 = Left 0.5
pointsForSeventy 12 = Left 0.5
pointsForSeventy a = Right a
Upvotes: 4