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)
To multiply decimals, first multiply as if there is no decimal. Next, count the number of digits after the decimal in each factor. Finally, put the same number of digits behind the decimal in the product.
Multiplying decimals is the same as multiplying whole numbers except for the placement of the decimal point in the answer. When you multiply decimals, the decimal point is placed in the product so that the number of decimal places in the product is the sum of the decimal places in the factors.
Therefore, 0.1 ,is padded with a trailing zero, making it 0.10, which gives it two decimal digits, the same as 0.01.
F# is very strict with numeric types. There are several reasons for this.
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 clearType 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
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
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