Advanced Syntax

Lambdas

Some functions require the user to specify an expression to evaluate for each item in an array parameter (for example, FILTER or MAP). These functions require more than just data to be provided, but instead expect another expression that is evaluated for each item in the array. For example, imagine a shape that has multiple child shapes that all have the "Value" shape data property, the follow expression will return an array which contains all children that have a value greater than 5:

=FILTER(this.children, child => child.Value > 5)

In this expression, the FILTER function is called on this.children (which returns all children for the current item), and for each child, will return a true/false value when the child's "Value" property is greater than 5. The FILTER function takes two parameters, the first is an array of values (in this case, this.children) and a expression to evaluate for each item (in this case, child => child.Value > 5).

The expression to evaluate in this case is called a lambda, and comes in the form of:

name => (operations using name)

name above tells the expression what to call each item in FILTER, and can be used as if it's a constant or a function. As another example, consider the following formula:

=MAP(ARRAY(1, 2, 3), x => x * x)

In this formula, the MAP function is called for each item in the array (the values 1, 2, and 3). For each item, the value is multiplied by itself, resulting in an array containing the square of each value: [1, 4, 9].

Nesting Lambdas

Lambdas can also be nested, for example if a function which expects a lambda parameter calls a function which itself expects a lambda in its lambda. When nesting functions that take lambdas, using different names for each lambda helps to ensure that each item can be referenced uniquely.

Consider the following formula:

=MAP(ARRAY(1, 2, 3), x => FILTER(@arr, y => y > x)

In this formula, the MAP function is called on an the array containing 1, 2, and 3. For each item in the array, the FILTER function is called, using the current shape's shape data property "arr", and filtering to include only items where the item is greater than the current value from the MAP function. For example, if @arr contained the array [1, 2, 3, 4], the above function would return: [[2, 3, 4], [3, 4], [4]]. If we walk through each step:

  1. MAP is called on [1, 2, 3]
  2. For each item in the array:
    • x = 1:
      • FILTER returns the array [1, 2, 3, 4] filtered to only include items above x (1), which is [2, 3, 4]
    • x = 2:
      • FILTER return the array filtered to only include items above x (2), which is [3, 4]
    • x = 3:
      • FILTER return the array filtered to only include items above x (3), which is [4]
    • No more items are in array, so the loop stops, returning each item found above as an array: [[2, 3, 4], [3, 4], [4]].

What’s Next