Let Expressions - Spicery/Nutmeg GitHub Wiki
The let-syntax is used to neatly encapsulate intermediate variables, so they are only visible in the parts of the program that need to see them. It has two versions:
- let-expression:
let DECLARATIONS in EXPRESSIONS endlet
- let-declaration:
let DECLARATIONS endlet
Let Expressions
The let-expression is the commonest form of let-syntax. It is used to define some intermediate variables that are then used inside an expression. For example:
let d := sqrt( x**2, y**2 )
in
x/d + y/d
end
Let Declarations
Modifiers
In a let-expression, the declarations can be annotated by the modifiers private
, public
or common
with the following rules:
- Any variable declared as
private
is entirely local to that scope, as you might expect. - Variables declared as
public
orcommon
are visible outside that scope, as if they were declared in the parent scope. - And variables declared as
common
cannot directly referenceprivate
variables. This is a modifier that is unique to Nutmug that is mainly useful when defining classes.
Note that, as an alternative to putting private
, public
or common
in front of the name, the declaration can be marked using the annotations @private
/@public
/@common
.
block/endblock
The block/endblock form is most useful for defining some functions whilst hiding some auxiliary variables. For example:
block
private x := ref(initial)
public countup := fun(): x!, x! <-- $$ + 1 end
endblock
Within block scopes, you may use let
as a synonym for private. So the above code can be written more tersely like this:
block
let x := ref(initial)
countup := fun(): x!, x! <-- $$ + 1 end
end
Files as block scopes
There are a couple of other block scopes in Nutmeg. Each compiled file forms a block scope with public default. This means it is possible to have private top-level definitions that are hidden from the rest of the program. e.g.
def factorial( n ):
fact( n, 1 )
enddef
@private
def fact( n, sofar ) =>>
if n <= 1:
sofar
else:
fact( n-1, b=n*sofar )
endif
enddef
Note that the default visibility for files is public
.
Classes as Block Scope
Class definitions also introduce block scopes with a default of public
.