All lessons

Numbers & Math

7 min · OCaml

Do math with whole-number operators.

OCaml · Numbers & Math0/5 cleared

Enemy 1 of 5

Whole-number operators and printing

This is one of the sharpest edges newcomers hit in OCaml: integers and floating-point numbers are entirely different types, and OCaml will not silently convert between them the way many other languages do. `5 + 5` (both integers) works fine, and `5.0 +. 5.0` (both floats) works fine, but `5 + 5.0` is a compile error — you cannot add an `int` and a `float` directly. Floats even use their own dedicated operators, with a trailing dot: `+.`, `-.`, `*.`, `/.` instead of `+`, `-`, `*`, `/`.

This might feel strict compared to languages that quietly promote an int to a float when needed, but it's a deliberate design choice: OCaml would rather force you to be explicit about a conversion (with functions like `float_of_int` and `int_of_float`) than silently lose precision or guess wrong about your intent.

For plain integers, the operators are the familiar `+ - * /`, following normal order of operations, with parentheses to override it. `/` between two integers performs integer division, discarding any remainder — `7 / 2` is `3`, not `3.5`.

Printing a number needs a dedicated function, since `print_endline` only accepts strings: `print_int` prints an integer with no trailing newline, so you typically follow it with `print_newline ()` to move to the next line. The `;` between the two calls sequences them — "do this, then do that" — which is how OCaml chains multiple side-effecting expressions together within one `let () = ...`.

You
Syntax Skeleton

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: 15