If Else in OCaml
Branching with if
and else
in OCaml is straightforward.
To run this OCaml program, you would typically save it in a file with a .ml
extension and use the OCaml compiler:
Note that in OCaml, you don’t need parentheses around conditions, but the then
and else
keywords are required. The if-then-else
construct is an expression in OCaml, which means it always returns a value.
OCaml doesn’t have a ternary operator like some languages, but the if-then-else
expression can be used in a similar way since it returns a value.
In OCaml, indentation is not significant for the language syntax, but it’s good practice to indent your code for readability. Also, OCaml uses semicolons to separate expressions in a sequence, not to end every statement like in some other languages.