“You are full of surprises, Mr Baggins!.”
—Gimli son of Gloin
One will often see C code in which a function is passed around together with its argument. Together they constitute a fate, a suspended computation which may be continued at any time by calling the function with its argument.
This arrangement is necessary in C because C functions are fixed at compile time, immutable at run time: The only way to express a pending computation is to specify the code and state separately.
Mythryl allows the two to be neatly combined:
#!/usr/bin/mythryl fun delayed_print string = \\ () = printf "%s\n" string; fate_a = delayed_print "Just"; fate_b = delayed_print "another"; fate_c = delayed_print "Mythryl"; fate_d = delayed_print "hacker!"; fate_a (); fate_b (); fate_c (); fate_d ();
When run this produces
linux$ ./my-script Just another Mythryl hacker! linux$
What has happened here is that the anonymous functions (thunk)s constructed
by the \\ () = printf "%s\n" string;
line of code are capturing the
string arguments visible to them.
The Mythryl
statement is actually a data constructor!
In principle, if we really wanted to, we could write our programs
constructing all of our datastructures entirely in terms of
statements capturing value, although the resulting code would not be
very pleasant to read. For example, we could constructs lists via
a function which captures two values and returns a thunk capable of
returning either on request. Here is a slightly simplified example
of such a function:
#!/usr/bin/mythryl Selector = FIRST | SECOND; fun cons (a, b) = \\ selector = case selector FIRST => a; SECOND => b; esac; x = cons( "abc", "def" ); printf "%s\n" (x FIRST); printf "%s\n" (x SECOND);
When run, the above yields:
linux$ ./my-script abc def linux$
Re-inventing the Mythryl list this way makes no sense, but using value capture to construct fates for later execution makes a lot of sense. You will see this pervasively in production Mythryl code that you read, and after using this technique for awhile you will wonder how you ever programmed without it.