A Tour of Morfa

Switch

Switch statement in Morfa should look familiar to a C or Java programmer:

func numberToText(num: int): text
{
    var result = "none";
    switch (num)
    {
        case (0) 
            { /* empty case requires braces */ }
        case (1) 
            { var one = "one"; result = one; }
        case (2,3) // case may contain a nonempty list of values
            result = "a few"; 
        default  
            result = "a lot";
    }
    return result;
}

unittest
{
    assert (numberToText(0) == "none");
    assert (numberToText(2) == "a few");
    assert (numberToText(4) == "a lot");
}

However, there are some differecences:

  • A single case branch may correspond to more than one value (for example case (2,3) above).
  • There is no fall-through, only the code from the matching branch (or default, if no case matches) is executed.
  • Each branch must be a single statement, a special case of which is a compound statement consisting of a list (possibly empty) of statements enclosed within braces { } (for example case (0) and case (1)).
  • break statement does not have any special meaning inside a switch. If the switch is in a loop then break exits that loop, otherwise it is invalid.

Besides integer types you may also switch on enum values (obviously) and text:

enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }

import morfa.Text.base: lowerCase;

func dayFromText(txt: text): Day
{
    switch (txt.lowerCase())
    {
        case ("mon","monday")    return Day.Monday;
        case ("tue","tuesday")   return Day.Tuesday;
        case ("wed","wednesday") return Day.Wednesday;
        case ("thu","thursday")  return Day.Thursday;
        case ("fri","friday")    return Day.Friday;
        case ("sat","saturday")  return Day.Saturday;
        case ("sun","sunday")    return Day.Sunday;
    }
}

func isWorkingDay(day: Day): bool
{
    switch (day)
    {
        case (Day.Saturday, Day.Sunday) 
            return false;
        default 
            return true;
    }
}

unittest
{
    assert (isWorkingDay(dayFromText("Tuesday")));
    assert (not isWorkingDay(dayFromText("Sun")));
}

Note that cases in the body of dayFromText are not exhaustive. You will get a runtime error if you call for example dayFromText("środa") (środa is Wednesday in Polish, but our code does not know this).