PreviousUpNext

5.2.8  Defining functions

Suppose we want to convert more than one number from Arab to Roman numerals. Repeating the whole case statement from the previous examples each time would be absurd; instead we want to define a function once, which we may then invoke by name as many times as we please:

    #!/usr/bin/mythryl

    fun to_roman( i ) = {

        case i
         1 => "I";
         2 => "II";
         3 => "III";
         4 => "IV";
         5 => "V";
         6 => "VI";
         7 => "VII";
         8 => "VIII";
         9 => "IX";
        10 => "X";
         _ => "Gee, I dunno!";
        esac;
    };

    printf "3 => %s\n" (to_roman 3);
    printf "5 => %s\n" (to_roman 5);
    printf "0 => %s\n" (to_roman 0);

When run the above produces

    linux$ ./my-script
    3 => III
    5 => V
    0 => Gee, I dunno!
    linux$

The above function declaration looks a lot like a conventional C function declaration. It is not, but it will do no harm for the time being if you think of it that way.

Notice the = between the parameter list and the body. Later we will see that it is needed to support curried functions. For now, just remember not to leave it out!

Also notice the semicolon at the end of the function definition. C is a bit irregular about when terminating semicolons are needed. Mythryl is perfectly regular: All complete statements end with a semicolon.

As with almost all modern languages (even contemporary Fortran!) Mythryl function definitions can be recursive:

    #!/usr/bin/mythryl

    fun factorial( i ) = {

        if (i == 1)   i;
        else          i * factorial( i - 1 );
        fi;
    };

    printf "factorial(3) => %d\n" (factorial(3));
    printf "factorial(5) => %d\n" (factorial(5));

When run the above produces:

    linux$ ./my-script
    factorial(3) => 6
    factorial(5) => 120
    linux$

Later we shall see more concise ways of writing the above code, but for now the above gets the job done just fine.


Comments and suggestions to: bugs@mythryl.org

PreviousUpNext