OCaml Common Pitfalls Using the wrong operator

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9

Example

In OCaml, there are different arithmetic operators for floats and integers. Additionally, these operators can only be used on 2 floats or 2 integers. Here are invalid expressions in OCaml

1.0 + 2.0
1 + 2.0
1 +. 2
1 +. 2.0

The correct expression for each of these respectively are

1. +. 2.
float_of_int 1 +. 2.
1 + 2
float_of_int 1 +. 2.

There is no automatic casting of integers to floats or vice-versa in OCaml. Everything is explicit. Here is a list of the integer and float operators

OperationInteger OperatorFloat Operator
Additiona + bc +. d
Subtractiona - bc -. d
Multiplicationa * bc *. c
Divisiona / bc /. d
Modulusa mod bmodfloat c d
ExponentiationN/ac ** d

Where a and b are integers and c and d are floats.



Got any OCaml Question?