Interesting case related to silent casting from Int literal to Float

I was converting one of my projects to elm 0.19 and encountered such case:
In 0.18 we had Color module with rgb function, so in code it looked something like that:

Color.rgb 128 128 128

I’m using style-elements package and I had to replace Color.rgb with Style.rgb. The last has the following signature:

rgb : Float -> Float -> Float -> Color

Where each parameter has a range from 0.0 to 1.0. Naturally, all elements became white :slight_smile:

Fortunately, in this particular case it was easy noticeable, but I wonder if such casting could be a reason for hard to spot bugs.

So the literal 128 is not an Int but rather a number. This is a special type that says “I haven’t decided yet if I want this to be an integer or a float”.

If it gets used in a function that requires integers then the compiler decides it is going to be an integer. If it gets used in a function that requires floats then the compiler will decide it’s a float. And if it gets used in a function that allows either then the compiler will let it stay as a number.

You can read more about it in the official guide.

Examples from the REPL:

// is integer division and requires two ints and returns an int. Dividing 10 by 3 gives us back the expected int.

> (//)
<function> : Int -> Int -> Int

> 10 // 3
3 : Int

/ is float division and takes two floats and returns a float. Dividing 10 by 3 gives us back the expected float.

> (/)
<function> : Float -> Float -> Float
> 10 / 3
3.3333333333333335 : Float

+ takes two number and gives us back a number. Adding 10 and 3 gives us back the expected number.

> (+)
<function> : number -> number -> number
> 10 + 3
13 : number
3 Likes

Interesting, I had never really got my head around how this works. Sometimes I might have an expression like

((start + offset) + (end + 10)) / 2

Where start : Float and end : Float but offset : Int. The compiler would then tell me that I need to convert offset explicitly to Float but would take the 10 and the 2 quite happily. I fixed the error but was always left a bit puzzled, but I see how it works now with the number type.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.