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 FloatIt 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?
Casting the int to a float explicitly will do absolutely nothing. The int will be promoted to a float for purposes of comparison anyway.
The reason you get different output is you perform a different computation: division behaves differently for integers and floating point numbers, except when the numerator is a multiple of the denominator.
Integers and floats are two different kinds of numerical data. An integer (more commonly called an int) is a number without a decimal point. A float is a floating-point number, which means it is a number that has a decimal place. Floats are used when more precision is needed.
As you probably know, both of these types are 32-bits. int can hold only integer numbers, whereas float also supports floating point numbers (as the type names suggest).
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With