Effects
A pure function is a function whose result depends only on its arguments. There must be no dependency on state, io, time, etc. for a function to be pure. Pure functions have very nice features such as being thread-safe and very easy for optimizing compilers. Nevertheless, pure functions alone are useless since all useful programs interact with some input to produce some output.
Effects are a means to model non-functional aspects of an otherwise pure function. In Fuzion, effects additionally provide a means to change the implementation of an effect used by a function. For example, a function might perform logging using an effect. Then, the caller of this function itself requires this effect unless it provides a handler for the logging effect.
Effectful Hello-World
As an introduction, let us implement a simple Hello World! using
a greeter
effect that provides an operation greet
:
Note that the effects listed when the Fuzion compiler analyzes this program
(click Effects!) is io.out
, not greeter
since greeter
is installed explicitly, but the installation
uses io.out
.
If we run main
directly without setting a greeting
effect, we will get an error:
In this case, the analysis for required effects (click Effects!)
shows greeter
since this effect is required to run this code.
To give a glimpse of the power of effects, we now run a slightly more
complex main
feature on a list of different implementations of
the greeter
effect. First, the same as before. Next, an implementation that prints
to the standard error stream instead. Then, one that is just silent and does not
greet at all. And finally, one that performs only the first greeting and then
returns, i.e., it stops any further calculation within main
and
directly returns from the call to use
.
Coroutines using Effects
Here is a small example defining a generator effect gen T
with an operation yield
. The effect is then used in a feature that
traverses a list to yield all the elements of that list.
Using State Effect to Count
The next example also traverses a list, but this time to count the number of
elements. For this, a state
effect is used that is incremented for
each element of the list that is traversed.