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

I am new to elms and functional programming in general. I had an incomprehensible type mismatch when performing the separation with the call to "show". This code creates a mismatch:

import Graphics.Element exposing (..) columns = 2 main = placePiece 10 placePiece: Int -> Element placePiece index = show (index/columns) 

The code causes this error:

Type mismatch between the following types in row 9, column 3-22:

  Int Float 

This is due to the following expression:

  show (index / columns) 

Which I read to mean that it expects, and Int, but got Float. But the show works with any type. If I use the word to force division by Int, I get the same error. But, if I hard code the numbers, for example. show (10/2) It works great.

So, what part of the above code expects to get Int?

+7
elm
source share
1 answer

Cause of error

Actually, in this case the compiler expects Float , but gets Int . Int is the index argument to the placePiece function, and it expects Float because Basics.(/) Expects Float arguments.

Why literal numbers work

When you just print the codes, the compiler can understand that although you use integers, you can use them as a Float instead of Int .

Error fixing

There are three ways to fix this error. If you really want to accept Int, but want floating point division, you 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 agree with the placePiece function with a floating point number, you can change the signature like:

 import Graphics.Element exposing (..) columns = 2 main = placePiece 10 placePiece: Float -> Element placePiece index = show (index/columns) 

If you need 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) 
+8
source share

All Articles