is it possible to create single if (without else) ? It is very usable to can use one if
Read the control structures : conditional section §6.7.2 of the Ocaml manual.
It is only possible to avoid the else
when the then
part (hence the entire if
expression) is of unit
type. For example
let x = 3 in
( if x > 0 then Printf.printf "x is %d\n" x );
x + 5
;;
should print x is 3
, and return as value 8.
The general rule is that if κ then τ
is equivalent to if κ then τ else ()
hence the "then part" τ
has to be of unit
type and the "else part" is defaulted to ()
so the entire if
is of unit
type.
let x = 3 in ( if x > 0 then "abc" ); x + 7 (*faulty example*)
won't even compile since "abc"
is not of unit
type (like ()
is)
You might sometimes use the ignore
function (from Pervasives) on the then
part to force it to be of unit
type (but that is worthwhile only when it has significant side-effects; if you replace "abc"
by ignore "abc"
then my faulty example would compile, but remains useless).
However, don't forget that Ocaml has only expressions (but no statements at all). Side-effecting expressions are usually of unit
type (but you could, but that is usually frowned upon, define a function which computes some non-unit
result and has a useful side-effect).
© 2022 - 2024 — McMap. All rights reserved.
if-statement
tag is inappropriate for Ocaml. Ocaml has no statements, only expressions ! – Bathyscaphe