Menu

Closures

Mark Anthony Taylor (Shyreman)

A closure implements a function within a function, and initializes an archetype variable to the enclosed
function.
Example:

(IntToInt f = 
    (closure (Int32 x) -> (Int32 y):
        (y = (x * x))
    )
)

The single most important feature of a closure is the ability to capture the local variables used in the
parent function.

(float EnumerateElements (IQuery query) (IContainer c) -> :
    (ElementCallback f = 
        (closure (IElement e) -> :
        (query.AddElement e)
        )
    )

    (EnumerateElements c f)
)

In the above example we captured the parent's IQuery interface, and can use it in the body of the
enumeration callback. Uses such as this greatly simplify many patterns, including enumeration and
strategy.

The input argument of a function or method for an archetype must be prefixed with the keyword closure
in order to accept closure arguments.

i.e
(function EnumerateElements (IContainer c) (closure ElementCallback cb)->(Int32 count):
    .....
)

Since Sexy emphasizes stack allocation, it implements closures by propagating parent stack frame
pointers to the archetype variable. Since the stack frame is only valid in the expression sequence in
which the closure is defined, it cannot be persisted for use outside that sequence. For that reason
containers and variables cannot be assigned a closure reference. Closure references can only be passed
to functions invoked within the expression sequence in which the closure is defined, and so can only be
invoked in a valid state.
~~~~~


Related

Wiki: Content