The Sway Reference Manual/Lazy Evaluation
Many functional languages feature delayed (or lazy) evaluation of function arguments, Unlike applicative order evaluation (used by C and Java), where function arguments are evaluated before they are bound to formal parameters, lazy evaluation delays evaluation until the actual values are needed. This is accomplished by passing the argument as a thunk, which is a data structure containing the actual expression forming the argument and the environment in which the argument would have been evaluated under applicative order.
Sway allows the programmer to decide whether or not lazy evaluation should be used. To signify lazy evaluation, the formal parameter is named starting with a dollar sign ($). When the actual value of the argument is needed, the force function is used to evaluate the argument expression in the thunk. Here is an example:
function f($x)
{
println("about to force...");
force($x);
}
f(println("hello"));
When this code is executed, we get the output:
about to force...
hello
Contrast this with the output of the following code, where the formal parameter is named normally:
function f(x)
{
println("about to force...");
force(x);
}
f(println("hello"));
When this new code is executed, we get the output:
hello
about to force...
This is because the println must be evaluated before its result is bound to the formal parameter x.