Skip to main content

Functions

A function lives on an object, next to that object's fields. Inside it, self is that object.

Declaring and Calling​

declare.stofPlayground ↗
rate: 2

fn total(units: int) -> float {
  units * self.rate
}

#[main]
fn main() {
  pln(self.total(21));
}
Output

fn declares a function, with its parameters and their types in parentheses and its return type after ->. You call a function through the object it's on, with a path: self.total(21), or self.billing.total(21) for one on a child object. There are no global functions in a document, so a bare total(21) doesn't find it.

Returning a Value​

The last expression in a function, with no ; after it, is what the function returns. return returns early:

return.stofPlayground ↗
fn grade(score: int) -> str {
  if (score >= 90) return 'A';
  if (score >= 80) return 'B';
  'C'
}

#[main]
fn main() {
  pln(self.grade(95));
  pln(self.grade(70));
}
Output

Two small rules: return x; needs its semicolon, and a semicolon after the last expression makes it a statement instead of the return value.

Parameters​

Arguments are cast to the parameter's type, so passing '5' to an int parameter gives 5. Parameters can have defaults, a default can use earlier parameters, and a ? makes a parameter optional (null when it isn't passed):

params.stofPlayground ↗
fn price(base: float, quantity: int = 1, total: float = base * quantity) -> float {
  total
}

fn label(name: str, note?: str) -> str {
  note != null ? `${name} (${note})` : name
}

#[main]
fn main() {
  pln(self.price(10));
  pln(self.price(10, 3));
  pln(self.price(quantity = 2, base = 5));   // named arguments, in any order
  pln(self.label('Pro'));
  pln(self.label('Pro', 'most popular'));
}
Output

Calling with a missing or extra argument is an error that says exactly what's wrong, like missing argument 'base' for price(base: float, ...).

What a Function Can See​

A function sees its own parameters and variables, and the document through self, super, and root. It doesn't see the variables of whatever called it. To use a value from the caller, pass it in:

scope.stofPlayground ↗
fn describe(tax: float) -> str {
  `tax is ${tax}`
}

#[main]
fn main() {
  const tax = 0.2;
  pln(self.describe(tax));
}
Output

That keeps every function self-contained: what it uses is either an argument or part of the document.

Arrow Functions​

An arrow function is a function written as an expression. It can be stored in a variable, and unlike a named function, it sees the variables around it:

arrows.stofPlayground ↗
#[main]
fn main() {
  const tax = 0.2;
  const with_tax = (amount: float): float => amount * (1 + tax);
  for (const price in [10, 20, 30]) {
      pln(with_tax(price));
  }
}
Output

Arrows Keep Their Variables​

An arrow keeps the variables it uses from where it was made, wherever it goes: into a field, a list, another function, or a library call like map or sort_by. Each time an arrow expression runs, it makes a new function value with the variables as they are right then, so arrows made in a loop each keep their own:

closures.stofPlayground ↗
fn adder(n: int) -> fn {
  (x: int): int => x + n
}

#[main]
fn main() {
  const add_one = self.adder(1);
  const add_ten = self.adder(10);
  pln(add_one(5), ' ', add_ten(5));             // 6 15

  const handlers = [];
  for (const i in 3) handlers.push_back((): int => i);
  pln(handlers.map((handler: fn): int => handler()));   // [0, 1, 2]
}
Output

What an arrow keeps is the variable itself, not a copy: assigning to it inside the arrow changes it where it came from, and a change made there later is seen by the arrow.

counter.stofPlayground ↗
fn counter() -> fn {
  let count = 0;
  return (): int => { count += 1; return count; };
}

#[main]
fn main() {
  const a = self.counter();
  const b = self.counter();
  a(); a();
  pln(a(), ' ', b());                           // 3 1

  let total = 0;
  [1, 2, 3].map((x: int) => { total += x; });
  pln(total);                                   // 6
}
Output

An arrow looks for a name in its own parameters and variables first, then in what it kept, and only then in the function calling it. So a variable with the same name where it's called doesn't change what it does:

lexical.stofPlayground ↗
fn run(rule: fn) -> float {
  const rate = 99;     // not the arrow's rate
  rule()
}

#[main]
fn main() {
  const rate = 0.5;
  pln(self.run((): float => rate));             // 0.5
}
Output

What an arrow keeps lives while your app runs the document. A document exported to text or BSTF stores an arrow as the function alone, and it keeps variables again when it runs.

Functions Are Values​

A function is a value like any other, of type fn. Store it in a variable or field, pass it to another function, and call it later:

values.stofPlayground ↗
discount: (price: float): float => price * 0.8

fn apply(price: float, rule: fn) -> float {
  rule(price)
}

fn double(price: float) -> float { price * 2 }

#[main]
fn main() {
  pln(self.discount(100));                     // a field holding a function
  pln(self.apply(100, self.discount));         // passed as an argument
  pln(self.apply(100, self.double));
}
Output

This is why Stof logic can be changed like data: replacing discount with a different function changes what every caller gets. A function value also keeps its own self, so it works on its own object wherever it's called from.

Function Signatures​

fn takes any function. A signature like fn(float) -> float takes only a function that can be called with a float and returns one, so a wrong rule fails where it's passed in, not somewhere deep inside:

signatures.stofPlayground ↗
fn(float) -> float discount: (price: float): float => price * 0.8

fn apply(price: float, rule: fn(float) -> float) -> float {
  rule(price)
}

fn label(price: float, prefix: str = '$') -> str { prefix + price }

#[main]
fn main() {
  pln(self.apply(100, self.discount));
  pln(self.apply(100, (p: float): float => p - 5));
  try {
      self.apply(100, self.label);   // returns a str, not a float
  } catch {
      pln('label is not a fn(float) -> float');
  }
}
Output

A function fits when it's compatible, not identical:

  • Parameters past the signature's need defaults (or ?), so fn(float) -> str fits label above.
  • A parameter can take more than the signature passes: unknown, a union that includes the type, a float for an int, or a prototype the signature's type extends.
  • The return type can be narrower. Leave it out (fn(str)) to take any return.
  • An async function fits by what it returns, with no Promise<..> in the signature.

An arrow with no return type returns nothing (void), so give it one: (x: int): int => x * 2. The return type takes the rest of the type, so fn(int) -> int | null returns an int or null. Parentheses group: (fn(str) -> str) | int is a function or an int. typeof is still 'fn', and typename gives the signature ('fn(float) -> float').

Calling Something That Might Not Be There​

Calling a function that doesn't exist is an error. Put ? before the . to get null instead:

null-safe.stofPlayground ↗
plugins: {}

#[main]
fn main() {
  const result = self.plugins?.on_save() ?? 'no on_save plugin';
  pln(result);
}
Output

?? gives a default when the left side is null. Null & Initialization has more.

Library Functions​

Functions that aren't part of the document, like pln, string and list helpers, or functions your app adds, come from libraries: Time::now(), 'stof'.upper(), App::notify(..). See Libraries.

Recursion​

this is the function that's running, so a function can call itself without using its own name:

recursion.stofPlayground ↗
fn fib(n: int) -> int {
  if (n <= 1) return n;
  this(n - 1) + this(n - 2)
}

#[main]
fn main() {
  pln(self.fib(10));
}
Output

Functions can also have attributes (#[test], #[main], or your own, see Attributes), run asynchronously (Async), and belong to types (Prototypes & Schemas). Next, Variables & References.