Kai D
Kai D

Reputation: 143

Simple Haskell Average Function Gives Couldn't Match Type Error

All the other average questions I've seen are much more complicated than what I need. I am very new to Haskell and I'm currently working through The Craft of Functional Programming 2nd Edition.

In chapter 3 there is an exercise to write a simple function to average 3 integers. The function type signature is provided and I used it in my solution. I wrote:

averageThree :: Int -> Int -> Int -> Float
averageThree a b c = (a + b + c) / 3

I use ghci for compilation and when I try and load my file I get "Couldn't match expected type Float' with actual typeInt'". How do I fix this error?

Upvotes: 0

Views: 475

Answers (3)

You should use Fractional, to support Real division:

averageThree :: Fractional a => a -> a -> a -> a
averageThree a b c = (a + b + c) / 3

Upvotes: 1

Lazersmoke
Lazersmoke

Reputation: 1741

(/) :: Fractional a => a -> a -> a, which means / takes two fractional numbers of the same type and returns a fractional number of the same type. You are giving it an Int as an argument, which is not fractional, and asking for a Float as output. You must convert your Int to a Float before giving it to /. Use fromIntegral :: Int -> Float. fromIntegral (a + b + c) / 3. You could also leave off the type signature and ask ghci for the inferred type.

Upvotes: 0

bheklilr
bheklilr

Reputation: 54058

The expression a + b + c will have type Int, and / is not even defined for Int. GHC will probably infer that 3 has type Float though. You have to explicitly cast the type in this situation, so you'd need to do

fromIntegral (a + b + c) / 3

The fromIntegral function takes an Integral a => a type like Int or Integer and converts it to a Num b => b type, which could also be Int or Integral, or Float, Double, Complex Double, and even custom numeric types.

Upvotes: 1

Related Questions