In Elm, why is this an Int-Float type mismatch?

3.6k views Asked by At

I am new to elm, and functional programming in general. I was getting a puzzling type mismatch when doing division with a call to 'show'. This code produces the mismatch:

import Graphics.Element exposing (..)

columns = 2
main = placePiece 10

placePiece: Int -> Element
placePiece index =
  show (index/columns)

The code produces this error:

Type mismatch between the following types on line 9, column 3 to 22:

  Int

  Float

It is related to the following expression:

  show (index / columns)

Which I read to mean that it expects and Int, but got a Float. But show works with any type. If I use floor to force the division into an Int, I get the same error. But, if I hard code the numbers, e.g. show (10/2) It works fine.

So what part of the code above is expecting to get an Int?

1

There are 1 answers

1
Apanatshka On BEST ANSWER

Reason for the error

Actually in this case the compiler is expecting a Float but getting an Int. The Int is the argument index of the placePiece function, and it expects a Float because Basics.(/) expects Float arguments.

Why literal numbers work

When you just hard code numbers, the compiler can figure out that although you're using whole numbers, you may want to use them as Float instead of Int.

Fixing the error

There are three ways to fix this error. If you really want to accept an Int but want floating point division, you'll have to turn the integer into a floating point number:

import Graphics.Element exposing (..)

columns = 2
main = placePiece 10

placePiece: Int -> Element
placePiece index =
  show (toFloat index / columns)

If you're ok with the placePiece function taking a floating point number you can change the type signature:

import Graphics.Element exposing (..)

columns = 2
main = placePiece 10

placePiece: Float -> Element
placePiece index =
  show (index/columns)

If you wanted integer division, you can use the Basics.(//) operator:

import Graphics.Element exposing (..)

columns = 2
main = placePiece 10

placePiece: Int -> Element
placePiece index =
  show (index//columns)