Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 40 ยท Language Basics

Operators and Type Conversions in OCaml

Learn why OCaml has separate integer and float operators, how to convert between types explicitly, operator precedence, the pipe operator and custom operators.

OCaml never converts numbers behind your back. Adding an int to a float is a type error, and that strictness is why the language has two sets of arithmetic operators and explicit conversion functions. Once you accept this, arithmetic becomes predictable.

Integer operators

OCAML
# 3 + 4;;
- : int = 7
# 10 - 3;;
- : int = 7
# 6 * 7;;
- : int = 42
# 17 / 5;;
- : int = 3
# 17 mod 5;;
- : int = 2
# - 5;;
- : int = -5

Also useful: abs, succ, pred, min, max, bitwise land, lor, lxor, lsl, lsr, asr, and ** is NOT integer power (it is a float operator).

Float operators

Every float operator has a dot:

OCAML
# 3.0 +. 4.5;;
- : float = 7.5
# 10. -. 0.5;;
- : float = 9.5
# 2.0 *. 8.0;;
- : float = 16.
# 1.0 /. 4.0;;
- : float = 0.25
# 2.0 ** 10.0;;
- : float = 1024.

Mixing them is rejected (the exact wording of the message varies between compiler versions):

OCAML
# 1 + 2.5;;
Error: The constant 2.5 has type float but an expression was expected of type int

Plus the standard float functions: sqrt, exp, log, sin, cos, floor, ceil, abs_float, and in the Float module Float.round, Float.of_int, Float.to_int.

Explicit conversions

OCAML
# float_of_int 7;;
- : float = 7.
# int_of_float 7.9;;
- : int = 7
# Float.of_int 3 /. 2.0;;
- : float = 1.5
# truncate (-2.7);;
- : int = -2
# Float.round 2.5;;
- : float = 3.

int_of_float truncates toward zero (it does not round). To round to the nearest integer use int_of_float (Float.round x). To compute an average of integers, convert first:

OCAML
let average a b = (float_of_int a +. float_of_int b) /. 2.0

Comparison and equality

The comparison operators are polymorphic: they work on all types.

OCAML
# 3 < 5;;
- : bool = true
# "apple" < "banana";;
- : bool = true
# 2 <> 3;;
- : bool = true
# [1; 2] = [1; 2];;
- : bool = true

Important: = is structural equality (compares contents), == is physical equality (same object in memory), and <> / != are their negations. Use = unless you have a reason not to. Comparing functions with = raises an exception at run time.

Boolean and string operators

  • &&, ||, not
  • ^ joins strings; @ joins lists; :: adds an element in front of a list.
OCAML
# "ab" ^ "cd";;
- : string = "abcd"
# [1; 2] @ [3];;
- : int list = [1; 2; 3]
# 0 :: [1; 2];;
- : int list = [0; 1; 2]

Precedence and associativity

From highest to lowest (simplified):

Operators Notes
function application f x binds tightest
** right associative
* / mod *. /. left
+ - +. -. left
:: right
^ @ right
= < > <> left
&& right
|| right
if, let, match, fun lowest

Function application beats everything, which is why f x + 1 means (f x) + 1. And why f -1 is a surprise: it parses as f - 1. Write f (-1).

OCAML
# let f x = x * 2;;
val f : int -> int = <fun>
# f (-1);;
- : int = -2

The pipe operator

|> passes a value to a function: x |> f means f x. It lets you read pipelines left to right:

OCAML
let result =
  [1; 2; 3; 4; 5]
  |> List.filter (fun n -> n mod 2 = 1)
  |> List.map (fun n -> n * n)
  |> List.fold_left (+) 0
(* 1 + 9 + 25 = 35 *)

Its cousin @@ applies a function with low precedence: print_endline @@ string_of_int 3.

Defining your own operators

Operators are ordinary functions with symbol names. Put them in parentheses to define or use them as functions:

OCAML
let ( +| ) a b = (a + b) mod 10
# 7 +| 6;;
- : int = 3

The first character of the symbol decides precedence: operators starting with + or - behave like addition. You can even redefine +, but that is rarely a good idea. Note that ( * ) needs spaces, otherwise (* starts a comment.

A stand-in: strict arithmetic and pipe

The stand-in below checks operand types like OCaml would and implements a tiny |> helper.

JS Stand-in: explicit conversions and the pipe

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which expression adds two floats?

    Float arithmetic uses dotted operators such as +. and *.
  2. 2. What is int_of_float 7.9?

    int_of_float truncates toward zero; it does not round.
  3. 3. What does f -1 parse as?

    Minus after an identifier is parsed as a binary subtraction. Write f (-1).
  4. 4. What is the difference between = and ==?

    = is structural equality; == tests whether two values are the same object in memory.
  5. 5. What does x |> f mean?

    The pipe passes its left operand as the argument of the function on the right.

Summary

  • Integers use + - * / mod; floats use +. -. *. /. **. They never mix.
  • Convert explicitly with float_of_int, int_of_float, Float.round and friends.
  • = is structural equality, == is physical; comparisons are polymorphic.
  • Function application binds tighter than any operator, so write f (-1).
  • |> builds readable pipelines; custom operators are plain functions.

Next: Tuples and unit