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?
Reason for the error
Actually in this case the compiler is expecting a
Float
but getting anInt
. TheInt
is the argumentindex
of theplacePiece
function, and it expects aFloat
becauseBasics.(/)
expectsFloat
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 ofInt
.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:
If you're ok with the
placePiece
function taking a floating point number you can change the type signature:If you wanted integer division, you can use the
Basics.(//)
operator: