Multiplying decimal and integer F#
f#, type-conversion
Solution
F# is very strict with numeric types. There are several reasons for this.
- 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
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`
- Simplicity. As there are no automatic type conversions, any conversions are immediately obvious and some mistakes become much simpler to spot.
Problem
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) ```