PreviousUpNext

10.9.6  Value Capture by Functions

One property which makes Mythryl functions more generally useful than the functions of (say) C is that Mythryl functions can capture values from their environment. This makes it cheap and easy to create specialized new functions on the fly at runtime.

Consider a function increment which adds one to a given argument:

    linux$ cat my-script
    #!/usr/bin/mythryl

    fun increment i
        =
        i + 1;

    printf "Increment %d = %d\n" 1 (increment 1);

    linux$ ./my-script
    Increment 1 = 2

More useful would be a function which can bump its argument up by any given amount needed, selectable at runtime.

One way to write such a function is by using currying:

    linux$ cat my-script
    #!/usr/bin/mythryl

    fun bump_by_k k i
        =
        i + k;

    bump_by_3  =  bump_by_k  3;
    bump_by_7  =  bump_by_k  7;

    printf "bump_by_3 1 = %d\n" (bump_by_3 1);
    printf "bump_by_7 1 = %d\n" (bump_by_7 1);

    linux$ ./my-script
    bump_by_3 1 = 4
    bump_by_7 1 = 8

But another way is to have an anonymous function capture a value from its lexical environment:

    linux$ cat my-script
    #!/usr/bin/mythryl

    fun make_bump k
        =
        \\ i = i + k;

    bump_by_3  =  make_bump  3;
    bump_by_7  =  make_bump  7;

    printf "bump_by_3 1 = %d\n" (bump_by_3 1);
    printf "bump_by_7 1 = %d\n" (bump_by_7 1);

    linux$ ./my-script
    bump_by_3 1 = 4
    bump_by_7 1 = 8

Here the anonymous function is capturing the value k present in its lexical environment and remembering it for later use.

Functions which have captured values in this way are often termed closures.

This value capture technique is often very convenient when constructing a fate of some sort in the middle of a large function with many relevant values in scope.

For another example of the usefulness of this technique see the Roll-Your-Own Object Oriented Programming tutorial.


Comments and suggestions to: bugs@mythryl.org

PreviousUpNext