Skip to content
LogoLogo

Functions

Functions take ;-separated parameters and return their result with with, or as a single expression.

functions.lithe
storage is record {
  total : uint;
}
 
(* Internal functions are called from the contract only. A body is a block;
   `with` gives the result. *)
pure function add(const a : uint; const b : uint) : uint is
  a + b
 
(* A block runs first, then the `with` expression is the result. *)
pure function hypotSquared(const a : uint; const b : uint) : uint is {
  const aa : uint := a * a;
  const bb : uint := b * b;
} with add(aa, bb)
 
(* Parameters are `const` unless declared `var`. Parameters are separated by `;`. *)
pure function clamp(var x : uint; const lo : uint; const hi : uint) : uint is {
  if x < lo then { x := lo; }
  if x > hi then { x := hi; }
} with x
 
(* A function with no result returns `unit`, so it has no `: type`. *)
function bump(const by : uint) is {
  storage.total := storage.total + by;
}
 
external function run(const a : uint; const b : uint) is {
  bump(clamp(hypotSquared(a, b), 1, 1_000));
}
 
(* Several results are a tuple. *)
external view function stats() : (uint, bool) is
  (storage.total, storage.total > 100)
  • var parameters can be reassigned inside the body. Callers are unaffected.
  • storage parameters are references to the storage a caller passes, which the function may write. See Parameters.
  • A function with no result type returns unit and is called as a statement: bump(...);.