Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying decimal and integer F#

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)
like image 234
Thiago Avatar asked Apr 25 '14 19:04

Thiago


People also ask

What is the rule for multiplying with decimals?

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.

What happens when you multiply a number by a decimal?

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.

Is 0.1 and 0.01 the same?

Therefore, 0.1 ,is padded with a trailing zero, making it 0.10, which gives it two decimal digits, the same as 0.01.


2 Answers

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.
like image 115
John Palmer Avatar answered Oct 12 '22 22:10

John Palmer


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

like image 42
theDarse Avatar answered Oct 12 '22 21:10

theDarse