References - Spicery/Nutmeg GitHub Wiki
A reference is an object with a single value, created using the Ref
constructor and whose contents are accessed using the postfix !
operator. Updating the contents of a Ref object needs the structure updating operator <--
because the simple assignment operator <-
only works on variables.
x := newVarRef( "Hello world" )
println( x! )
### Prints: Hello world
x! <-- "Bye for now"
println( x! )
### Prints: Bye for now
Key Use-Case for Operators: Assignment to Shared Variable
Because Nutmeg does not provide assignable variables that are accessible in nested lambdas, a well-know idiom for generators needs adapting. Here's the idiom being used for a generator for the half-open interval 0 to n:
def upto( n ):
var i := 0;
lambda:
if i < n:
i ### NOT ALLOWED
i <- i + 1 ### NOR THIS
else:
return Stop()
endif
end
end
References provide the way around this:
def upto( n ):
val i := newVarRef( 0 ); ### val can be used in nested lambdas
lambda:
if i < n:
i! ### Allowed :)
i! <-- i! + 1 ### Must use <--
else:
return Stop()
endif
end
end