Switch in Standard ML

Here’s a basic switch.

val i = 2
val _ = print ("Write " ^ Int.toString(i) ^ " as ")
val _ = case i of
    1 => print "one\n"
  | 2 => print "two\n"
  | 3 => print "three\n"

You can use a case statement to handle multiple expressions. Standard ML does not have a default case, so we use NONE as an illustrative example.

val today = Date.dayOfWeek (Date.fromTimeLocal (Time.now ()))
val _ = case today of
    Date.SATURDAY => print "It's the weekend\n"
  | Date.SUNDAY => print "It's the weekend\n"
  | _ => print "It's a weekday\n"

A similar construct to the if/else logic can be achieved using a case statement. Non-constant expressions can be used within the case branches.

val t = Time.now ()
val hour = Time.h ms_toTime (Time.toMilliseconds t) div Time.hour
val _ = case (hour < 12) of
    true => print "It's before noon\n"
  | false => print "It's after noon\n"

Standard ML does not support type switching directly. We typically use pattern matching to handle types. Here for illustration, we use a simple case to mimic type handling.

fun whatAmI x = case x of
      BOOL _ => print "I'm a bool\n"
    | INT _ => print "I'm an int\n"
    | _ => print ("Don't know type\n")

val _ = whatAmI (BOOL true)
val _ = whatAmI (INT 1)
val _ = whatAmI (STRING "hey")

Output when running the program:

Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type

Next example: Arrays.