Modules¶
A program can be split across files. Each file is a module named by its path, so there is nothing to declare and no file that only lists other files. This program has three:
modules/
main.stn
stats.stn
text/
pad.stn
main.stn is the entry file, the one you run:
use stats
use text.pad.left as pad_left
scores = [90, 72, 85, 64]
print("mean:", stats.mean(scores))
print("best:", stats.best(scores))
for score in scores:
print(pad_left(str(score), 5))
stats.stn is the module stats:
// summary statistics for lists of ints
pub fn mean(xs: list[int]) -> int:
ret total(xs) / xs.len()
pub fn best(xs: list[int]) -> int:
top = xs[0]
for x in xs:
if x > top:
top = x
ret top
// only stats.stn can call this, since it is not pub
fn total(xs: list[int]) -> int:
sum = 0
for x in xs:
sum = sum + x
ret sum
and text/pad.stn is the module text.pad:
// pads s with spaces on the left until it is width characters long
pub fn left(s: str, width: int) -> str:
while s.len() < width:
s = " " + s
ret s
stone run modules/main.stn prints
mean: 77
best: 90
90
72
85
64
Using a module¶
The entry file’s directory is the program’s root, and a module’s name is its path from there,
with . between the parts and without .stn. use loads a module by that name:
use statsbinds the module, and you call its functions asstats.mean(scores).use text.pad.leftbinds one function,left, which you call directly.aspicks another name, as inuse text.pad.left as pad_left.
A name is always the whole path from the root, whichever file the use is in, so moving a file
only changes how others name it. use statements come first in a file.
pub¶
A function is private to its file unless it starts with pub, and so is a struct, an enum, or a
trait (pub struct Point:), which use stats.Point imports. main.stn can call
stats.mean and stats.best, but not stats.total, which only stats.stn itself can use. Two
modules can each have a private function with the same name without clashing.
What a module holds¶
A module other than the entry file holds only use statements and definitions: functions,
structs, enums, traits, and impl blocks. Using a module never runs any code, so two modules may use each other. A module’s functions see their own
parameters and locals, the functions of their own file, and what that file uses, but never the
entry file’s variables.
The checker infers types across every file together, so a function in a module gets its types from how the program calls it.
See Modules for every rule, and Using packages for using modules from other projects.
Next, Errors.