If Else in Standard ML

Branching with if and else in Standard ML is straightforward.

(* Here's a basic example. *)
if 7 mod 2 = 0 then
    print "7 is even\n"
else
    print "7 is odd\n";

(* You can have an if statement without an else. *)
if 8 mod 4 = 0 then
    print "8 is divisible by 4\n";

(* Logical operators like andalso and orelse are often useful in conditions. *)
if 8 mod 2 = 0 orelse 7 mod 2 = 0 then
    print "either 8 or 7 are even\n";

(* A let expression can precede conditionals; any variables
   declared in this expression are available in the current
   and all subsequent branches. *)
let
    val num = 9
in
    if num < 0 then
        print (Int.toString num ^ " is negative\n")
    else if num < 10 then
        print (Int.toString num ^ " has 1 digit\n")
    else
        print (Int.toString num ^ " has multiple digits\n")
end;

To run this Standard ML program, you would typically use an SML interpreter or compiler. For example, if you’re using SML/NJ (Standard ML of New Jersey), you could save this code in a file named if_else.sml and run it like this:

$ sml if_else.sml
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that in Standard ML, you don’t need parentheses around conditions, but semicolons are used to separate expressions. The then and else keywords are required for if-then-else expressions.

Standard ML doesn’t have a direct equivalent to Go’s ability to declare variables in the condition of an if statement. Instead, we use a let expression to declare variables before the conditional.

There is no ternary if operator in Standard ML, similar to Go. You’ll need to use a full if-then-else expression even for basic conditions.