Computer Science Canada

[O'Caml Tutorial] From the Bottom Up 1: Numbers

Author:  wtd [ Sat Sep 25, 2004 3:01 pm ]
Post subject:  [O'Caml Tutorial] From the Bottom Up 1: Numbers

O'Caml takes a rather interesting approach to numbers. Since it's a statically and strongly typed language, there is no automatic coercion as exists in languages like C and Pascal. In C (or C++), when an integer is added to a floating point number, the compiler automatically casts the integer to a floating point number, and the entire expression results in a floating point number.

code:
42 + 1.2 /* yields 43.2 */


The other mathematical operators behave in the same way, automatically converting numbers.

Now, to explain what constitutes an integer and a floating point number in O'Caml.

Any number consisting of integers and underscores is an integer. The fact that underscores can be inserted into numbers in this manner makes it possible to break a large number up into meaningful blocks, much as North Americans would use a comma to accomplish the same goal.

code:
42
1000
1_000
10_00


Any number that contains a decimal point is labeled a floating point number. As a convenience, when writing floating point numbers that are really just integers, zeroes following the decimal point can be left out.

code:
42.0
42.
3.14
3.1_4


The operators which act on numbers are not polymorphic. Integers and floating point numbers have their own sets of operators.

code:
2 / 1
3 * 4
42 - 7
1 + 1


code:
8.4 /. 2.
5. *. 8.2
23. -. 1.
1. +. 1.


Of course, it's possible to convert integers to floating point numbers and vice versa.

code:
5. -. float_of_int 32
int_of_float 6. * 4


Though there are separate operators for math, logical comparison operators work equally well for both, though one cannot compare a float to an int without an explicit conversion.

code:
3 > 4
5. < 8.7
4.3 > float_of_int 2


All of this, though seemingly onerous, makes it possible for the compiler to cach a whole category of potential logic errors which go unchecked in less strict languages.


: