Atrocitas
Atrocitas

Reputation: 45

Cant figure out what type signature I need for this simple interest function

So im trying to make a recursive simple interest function and i cant for the life of me figure out what type signature i need to use. Here is my code:

interest :: (Fractional a) => a-> a-> a-> a
interest p r 0 = p
interest p r t = (1 + (p/100))*interest p r (t-1)

this code gives me the error "Could not deduce (Eq a) arising from the literal `0' from the context: Fractional a bound by the type signature for: interest :: forall a. Fractional a => a -> a -> a -> a "

but when I try changing the constraint to (Eq a) it tells me "possible fix (Fractional a)

can someone help me out?

Upvotes: 2

Views: 101

Answers (2)

developer_hatch
developer_hatch

Reputation: 16224

Is worth to mention that you can find out the type by doing this "little hack", don't you tell the type manually, let Haskell think for you when you are stuck like this:

interest p r 0 = p
interest p r t = (1 + (p/100))*interest p r (t-1) 

Like that, the code compiles just fine, then go to the terminal and just do:

:t interest
interest :: (Eq t1, Fractional t2, Num t1) => t2 -> t3 -> t1 -> t2

if you replace the letters and remove the extra type class Num (because in your case you want Fractional instances), it's exactly the same as the Willem answer:

t1 ==> a ; t2 ==> a ; t3 ==> a

interest :: (Eq a, Fractional a) => a -> a -> a -> a

But it is always better to think, what type do you really need and why?

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476709

The check on 0 in the first clause requires a to be an instance of the Eq typeclass as well, so you should add this to the signature:

interest :: (Eq a, Fractional a) => a-> a -> a -> a
interest p r 0 = p
interest p r t = (1 + (p/100))*interest p r (t-1)

Upvotes: 4

Related Questions