Documentation
Guides
Functions

Functions

Basic syntax

In Squiggle, function definitions are treated as values. There's no explicit return statement; the result of the last expression in the function body is returned. If you need to define local variables in functions, you can use blocks. The last expression in the block is the value of the block:

Anonymous Functions

In Squiggle, you can define anonymous functions using the {|...| ...} syntax. For example, myMultiply(x, y) = x * y and myMultiply = {|x, y| x * y} are equivalent.

Squiggle functions are first-class values, meaning you can assign them to variables, pass them as arguments to other functions, and return them from other functions.

Function Visualization

The Squiggle viewer can automatically visualize functions that take a single number as input and return either a number or a distribution, without the need for manual plots:

  1. (number) => number
  2. (number) => distribution

When Squiggle visualizes a function, it automatically selects a range of input values to use. The default range of input values is 0 to 10.

You can manually set the range in the following ways:

  • With Plot.numericFn or Plot.distFn plots, using the xScale parameter
  • Through the chart's settings in the UI (look for a gear icon next to the variable name)
  • With parameter annotations (explained below)

Parameter Annotations

Function parameters can be annotated with domains to specify the range of valid input values.

Examples:

  • x: Number.rangeDomain(5, 10)
  • x: [5, 10] — shortcut for Number.rangeDomain(...)

Annotations help to document possible values that can be passed as a parameter's value.

Annotations will affect the parameter range used in the function's chart. For more control over function charts, you can use the Plot module API.

Domains are checked on function calls; f(x: [1,2]) = x; f(3) will fail.

We plan to support other kinds of domains in the future; for now, only numeric ranges are supported.

Annotation Reflection

Domains and parameter names can be accessed by the fn.parameters property.