Operators

About all diferent types of operators syntax in Ocaml.


Table of operators

OperatorsMeaning
+Integer addition
- (infix)Integer subtraction.
*Integer multiplication.
/Integer division. Raise Division_by_zero if second argument is zero.
modInteger modulus. Raise Division_by_zero if second argument is zero.
landBitwise logical “and” on integers.
lorBitwise logical “or” on integers.
lxorBitwise logical “exclusive or” on integers.
lslBitwise logical shift left on integers.
lsrBitwise logical shift right on integers.
asrBitwise arithmetic shift right on integers.
+.Floating-point addition.
-. (infix)Floating-point subtraction.
*.Floating-point multiplication.
/.Floating-point division.
**Floating-point exponentiation.
@List Concatenation
^String Concatenation
!Dereferencing
=Structural Equality
<>Structural Inequality
<Less than
<=Less than or Equal
>Greater than
>=Greater than or Equal
&&Logical AND

Especial keywords

when keyword

Similar to an if statement, but designed to be used in a pattern matching. Returns an expression.

let rec mem x list =
	match list with 
	| [] -> false
	| h::_ when h = x -> true
    | _::t -> mem x t

ref keyword

Example: How to count++ inside a statement

Using a reference type ref allows to mutate the value of count in anywhere, like inside functions.

let count = ref 0 in

To increment count inside a fold function, we can use the := operator, an assignment operator for reference types.

let same_length lst1 lst2 =
  let len1 = length lst1 in
  let len2 = length lst2 in
  let count = ref 0 in
  if len1 > len2 then      
    fold 
    (
      fun acc e -> 
        if !count < len2 then 
          (count := !count + 1; e::acc) 
        else acc
    ) 
    [] 
    (lst1)   
  else 
    lst1

!count to dereference the reference type and get the actual integer value. count := !count + 1 statement inside the lambda function to increment count for each element that is added to the new list.

rec keyword

Specifies that a function can call to itself. Essential for implementing algorithms that require repetitive or iterative processes.

let rec function_name parameters =
  (* function body *)