Afonso Matos
Afonso Matos

Reputation: 2476

Haskell error on number operations

I've been searching for god knows how long, but couldn't get this piece of code to work:

solution n = 3/2*((n-n`mod`3)+3)

It compiles but when I call it, it throws two errors, the first one being

No instance for (Integral a0) arising from a use of `solution'

Here is what I'm trying to achieve

solution 9 = 3/2* ((n-n`mod`3)+3) = 3/2 * ((9-0)+3) = 3/2 * (12) = 18

Upvotes: 1

Views: 37

Answers (1)

Shaun the Sheep
Shaun the Sheep

Reputation: 22762

Haskell won't let you add the Fractional (3/2) to the Integral

((n - n `mod` 3) + 3)

without explicitly telling it that you want to by adding a fromIntegral to the latter. So

solution n = 3/2 * fromIntegral ((n-n`mod`3)+3)

should work.

There's quite a good overview of all the numeric types in Real World haskell. I never remember the details though, and mostly just add in a fromIntegral whenever it's required.

Upvotes: 2

Related Questions