Lambdas in Tines

💡Note

Lambdas are a custom, reusable function that you create using the LAMBDA function. This function is a little different from other functions because you specify the placeholders as the arguments to the function.

LAMBDA(a, b, a + b)

Here a and b are the arguments that will need to be passed when the lambda is called and the a + b is the expression that will be evaluated when the lambda is called.

There are three ways of using lambdas.

Immediately invoked 

First they can be immediately invoked i.e. LAMBDA(a, b, a + b)(1, 2). This will create a function to add two numbers together and then immediately call it. This might not seem very useful, but it can help avoid repetition in cases where you need to re-use the same calculation in multiple places.

For example if you wanted to check if the current time is between 9 and 5 you might do something like this:

IF( 
  AND(
   DATE("now", "%H") >= 9, 
   DATE("now", "%H") < 17, 
  ), 
  "office hours", 
  "after hours" 
)

Using a lambda you could avoid this repetition like so:

LAMBDA( 
  current_hour, 
  IF( 
    AND( 
      current_hour >= 9, 
      current_hour < 17, 
    ), 
    "office hours", 
    "after hours" 
  ), 
)(DATE("now", "%H"))

With an Array function 

The next way you can use Lambdas is as an argument to the functions MAP_LAMBDA, FILTER, FIND and REDUCE. For example, let's imagine we have the following array of data in a field called fruit:

[ 
  { 
    "name": "apple", 
    "in_stock": 0
  }, 
  {
    "name": "banana", 
    "in_stock": 5 
  }, 
  { 
    "name": "pear", 
    "in_stock": 6 
  } 
]

If we wanted to find all the items that are in stock we could write the following:

FILTER(fruit, LAMBDA(item, item.in_stock > 0))

Or if we wanted to find the item with the name pear we could do

FIND(fruit, LAMBDA(item, item.name = "pear"))

Or if we wanted to extract all the names we could do this:

MAP_LAMBDA(fruit, LAMBDA(item, item.name))

As a LOCAL or RESOURCE 

The final way you can use lambdas is to assign them to LOCAL or to a RESOURCE and then call them from somewhere else. This can be a great way of defining your own reusable bits of functionality.

Here we have created a lambda for defanging URLs and stored it in a RESOURCE. The lambda looks like this:

LAMBDA( 
  url, 
  url 
    |> REPLACE(%, ".", "[.]") 
    |> REPLACE(%, "http", "hxxp") 
)

Ensure the lambda in the Resource, is defined inside of single value mode:

With this in place, we can use it from any story like so:

RESOURCE.my_lambdas.defang(url)
Was this helpful?