Local functions and local value captures/Local function examples
This page shows (in no particular order) usage examples of Local Functions (and in some cases, value capture).
Mutables
The Mutables library with comes with Analytica provides an example that may be educational. Of course, if you need a mutable, we recommend using the library, but here we show how mutables are implemented using Local functions and local value captures.
Analytica's design intentionally excludes global Side effects from a Definition. But in rare cases, sometimes while debugging, it can be useful to "log" some data in memory without creating a data-dependency. We call a global in-memory storage that can be set, changed and read without maintaining any dependencies a mutable. The Mutables library provides a convenient set of functions for using mutables, which themselves are implemented via local functions and value capture.
A mutable is created with
Function MutableNew() ::= Local val := null; Array(Struct_Mutable, [ Function get( ) : val Do get, Function set( x ) : (val := x) Do set ])
where
- Index
Struct_Mutable ::= [ 'get', 'set' ]
The local, val
, holds the value of the mutable, and is captured by the two local functions that are returned in a struct by MutableNew. The get()
function reads the current value saved in val
, and set(x)
sets its value. The storage for val
outlives the call to MutableNew -- it is only released once both local functions are released.
Once you have a variable defined as:
- Variable
MyMutable ::= MutableNew()
You can read the current value using:
Function get( ) := MyMutable[Struct_Mutable='get'] Do get()
The function MutableGet in the Mutables library encapsulates this for you.
Enable comment auto-refresher