Pregunta

I'm learning f#. Considering this function:

let mult (a:decimal) (b:int) : decimal = a * b

When I try to compile I get this error: Error 1 Type constraint mismatch. The type int is not compatible with type decimal

Why the compiler does not accept this?

PS: When I explicity convert it does compile:

let mult (a:decimal) (b:int) : decimal = a * decimal(b)
¿Fue útil?

Solución

F# is very strict with numeric types. There are several reasons for this.

  1. Precision - 4.0 * 8.5 might not be exactly equal to 4*8.5 due to precision loss when converting to floating point. By forcing you to convert 4 to 4.0 the language has made that precision loss clear
  2. Type inference. Functions need to have concrete argument types. If we allowed implicit conversion from int to float, it would not be clear what the type of a should be in this example

    let test a = a + 1.0
    

    as both int and float could be valid types for a. (This can be avoided through inline functions where there are less restrictions on argument types and by using some functions like genericZero and genericOne

  3. Simplicity. As there are no automatic type conversions, any conversions are immediately obvious and some mistakes become much simpler to spot.

Otros consejos

This is actually a design feature of the language. The goal was to minimize side effects, and as such implicit conversion between these two data types was not included. The basic idea here is that the language will allow you to do this, but you must be aware you are doing it rather than simply not paying attention and multiplying two numbers with a possible unintended side effect

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top