OCaml provides below conditional expression statements

  • Simple Basic If Statement
  • If else statement

OCAML If conditional expression

Syntax

if Conditional_expression then  expression statements

Conditional_expression evaluated to true or false, If true, expression statements are executed.

Here is an example

let number: int = 10;;

if number > 0 then  print_string "Number is positive\n";;

OCAML If then else expression

If conditional expressions are used to evaluate and execute based on conditional statements.

Syntax

if Conditional_expression then  expression_statements else expression_statements2

Conditional_expression is evaluated to true or false, If true, expression_statements1 is executed, else expression_statements2 is executed.

Here is an example

let number: int = 10;;

if number > 0 
    then  print_string "Number is Positive\n";;
    else print_string "Number is Negative\n";;

If there are multiple statements inside then and else statements, Begin and End blocks are used.

Begin and End keywords are replacements of parenthesis.

Here is an example for a parenthesis

let number: int = 10;;

if number > 0 
    then  print_string "Number is Positive\n";;
    else (print_string "Number is Negative\n";;)

Replace parenthesis with Begin and End.

let number: int = 10;;

if number > 0 
    then  print_string "Number is Positive\n";;
    else Begin 
        print_string "Number is Negative\n";
        End