Expressions are the building blocks of a functional language.
Expressions have:
Values are a type of expression. All values are expressions, but not all expressions are values.
3110;;
- : int = 3110
In this example, 3110 is a value. 3110 evaluates to the int 3110 (as demonstrated by - : int = 3110
true;;
- : bool = true
Here true evaluates to a boolean
3110 > 2110;;
- : bool = true
This expression evaluates to true, because the integer 3110 is greater than the integer 2110.
"big";;
- : string = "big"
Here, big is a string. We can also concatenate strings:
"big " ^ "red";;
- : string = "big red"
This expression evaluates to another string
We can also do arithmetic
2.0 * 3.14
File "[6]", line 1, characters 0-3:
1 | 2.0 * 3.14
^^^
Error: This expression has type float but an expression was expected of type
int
Wait! What happened there? OCaml gave us an error message. This might surprise you, but * is the integer multiplication operator. To multiply floats, we need to use *.. This is a language design feature, so no complaining!
2.0 *. 3.14
- : float = 6.28
There, that worked as expected :). This also applies to other arithmetic operators too!
OCaml infers types. It still checks types (unlike Python).
Compilation will fail if the compiler cannot correctly infer the types. You can also manually specify types with (e : t)
(3110 : int);;
- : int = 3110
Note that this is NOT a cast. It will fail if you use it as one.
(3110 : bool);;
File "[9]", line 1, characters 1-5:
1 | (3110 : bool);;
^^^^
Error: This expression has type int but an expression was expected of type
bool