is it possible to create single if (without else) ? It is very usable to can use one if
You can use an if statement without a else if it returns a value of type unit (basically when it only does something). However, in your case, you want to return a value of type int and as such the else branch is mandatory. It can nonetheless be shortened using else if statements.
Most OCaml programmers do a lot of their loops via recursive functions. However, there are two imperative loops: a conventional while loop, and a counting for loop like that of Algol 60.
Using begin ... So the begin and end are necessary to group together multiple statements in a then or else clause of an if expression. You can also use plain ordinary parentheses ( ... ) if you prefer (and I do prefer, because I loathe Pascal :-).
The value of a let definition is the value of it's body (i.e. expr2). You can therefore use a let anywhere OCaml is expecting an expression. This is because a let definition is like a syntactially fancy operator that takes three operands (name, expr1 and expr2) and has a lower precedence than the arithmetic operators.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With