PreviousUpNext

5.7.11  Mythryl Functions

Code blocks aside, the core differences between basic SML and Mythryl function syntax are that

    fun f x = x;                      # Monocase form.

    fun f [] => printf "Empty\n";     # Multicase form.
        f x  => printf "Nonempty;
    end;

    fun f x = g x                     # Muturally recursive case.
    also                              # Note lack of semicolon before 'also':
    fun g x = f x;                    # semicolon always marks a complete construct.

    \\ x = x;                         # Monocase form of anonymous function.

    \\ [] => printf "Empty\n";        # Multicase form of anonymous function.
       x  => printf "Nonempty\n";
    end;

    {. printf "Foo\n"; }              # Equivalent to   \\ () = printf "Foo\n";

    {. #x == #y; }                    # Equivalent to   \\ (x, y) = (x == y);

The latter two forms are intended to facilitate application-programmer creation of functions which can be used like traditional iterative constructs. For example given the definition

    fun foreach []         thunk =>  ();
        foreach (a ! rest) thunk =>  { thunk(a);   foreach rest thunk; };
    end;

(which is in fact part of the Mythryl standard library) one can then write code like

    foreach [ "red", "green", "blue" ] {.
        printf "Color %s encountered\n" #color;
    };

thus obtaining most of the convenience of hardwired foreach loops in languages like Python without having to hammer each such construct explicitly into the compiler proper.

A more typical use of this construct would be to list all the files in the current directory:

    foreach (dir::entry_names ".") {. printf "%s\n" #filename; };

Since the standard library infix function invocation 1 .. 10 generates a list [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] one can also write loops like

    foreach (1 .. 10) {.
        printf "Loop %d\n" #i;
    };

although the explicitly constructed list makes this inefficient for large iteration counts.


Comments and suggestions to: bugs@mythryl.org

PreviousUpNext