1

This code:

division :: Double -> Int -> Double
division x k = x / k

gives me:

Prelude> :l main
[1 of 1] Compiling Main             ( main.hs, interpreted )

main.hs:2:20: error:
    • Couldn't match expected type ‘Double’ with actual type ‘Int’
    • In the second argument of ‘(/)’, namely ‘k’
      In the expression: x / k
      In an equation for ‘division’: division x k = x / k

I'm new to haskell, so could you please explain what the issue here is?

Sven
  • 1,014
  • 1
  • 11
  • 27
  • 5
    Many programming languages allow "numeric promotions", automatically converting numeric data types according to some rules, e.g. integers can be turned into floating point values. Haskell does not follow this path: no numeric conversion is done automatically, and operations like `+` or `/` require operands having the same type. One then has to manually convert values, when needed, using e.g. `fromIntegral`. (However, numeric literals like `5` are always taken at the right type: `5+x` will work, no promotion needed). – chi Jan 15 '23 at 20:36

1 Answers1

5

Because the first parameter is a Double and the second an Int. The (/) :: Fractional a => a -> a -> a requires that the two operands and the result all have the same type and are members of the Fractional type: the two operands are different here, and Int is of course not a member of the Fractional typeclass.

You can convert the Int to a Double first, with fromIntegral :: (Integral a, Num b) => a -> b:

division :: Double -> Int -> Double
division x k = x / fromIntegral k
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555