Operators
About all diferent types of operators syntax in Ocaml.
Table of operators
Operators | Meaning |
---|---|
+ | Integer addition |
- (infix) | Integer subtraction. |
* | Integer multiplication. |
/ | Integer division. Raise Division_by_zero if second argument is zero. |
mod | Integer modulus. Raise Division_by_zero if second argument is zero. |
land | Bitwise logical “and” on integers. |
lor | Bitwise logical “or” on integers. |
lxor | Bitwise logical “exclusive or” on integers. |
lsl | Bitwise logical shift left on integers. |
lsr | Bitwise logical shift right on integers. |
asr | Bitwise 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 *)