Lambda

params => expression
Lambda( params, expression )
Lambda( params, expression )
Lambda( params, expression )
lambda_( params, expression )
Lambda { params => expression }
Lambda( params, expression )

Description

The Lambda function is an anonymous function that performs lazy execution of custom code. It allows you to organize and execute almost any of the Fauna Query Language statements.

A Lambda can take zero or more parameters. Lambdas that accept multiple parameters must use a params array to represent all of the parameters. In this case, the items inside the params array are the arguments, not the array itself. The params array must have the same number of items as the caller provides, or an error occurs.

When a caller of a Lambda includes multiple parameters, such as when processing index entries with multiple values fields, your function might not need every item in the params array. Instead of creating a name for an unneeded parameter, you can use an _ (underscore) instead; it signals that the function should ignore that parameter.

The Lambda parameters may be accessed inside the Lambda code using the Var statement (except the _ parameter; it is not a named variable, it is a placeholder for a variable that should be ignored).

Two functions are considered equal if their syntax is identical. For example:

Equals(Query(Lambda('a', 5)), Query(Lambda('a', 5)))
true

Parameters

Argument Type Definition and Requirements

params

A single Value, or an array of zero or more Values.

expression

FQL expression

An FQL expression to be evaluated.

Returns

The evaluation of the expression.

Examples

  1. The following query uses the Map function to provide a single argument to the Lambda. The Lambda takes the parameter called name, resolves it to the value "Hen ", and then provides it to the first parameter to concatenate with the string "Wen". The result of "Hen Wen" is then returned.

    try
    {
        Value result = await client.Query(
            Map(Arr("Hen "), name => Concat(Arr(name, "Wen")))
        );
        Console.WriteLine(result);
    }
    catch (Exception e)
    {
        Console.WriteLine($"ERROR: {e.Message}");
    }
    Arr(StringV(Hen Wen))
    result, err := client.Query(
    	f.Map(
    		f.Arr{"Hen "},
    		f.Lambda("name", f.Concat(f.Arr{f.Var("name"), "Wen"}))))
    
    if err != nil {
    	fmt.Fprintln(os.Stderr, err)
    } else {
    	fmt.Println(result)
    }
    [Hen Wen]
    System.out.println(
        client.query(
            Map(
                Arr(Value("Hen ")),
                Lambda(
                    Value("name"),
                    Concat(Arr(Var("name"), Value("Wen")))
                )
            )
        ).get());
    ["Hen Wen"]
    client.query(
      q.Map(
        ['Hen '],
        q.Lambda('name', q.Concat([q.Var('name'), 'Wen'])),
      )
    )
    .then((ret) => console.log(ret))
    .catch((err) => console.error('Error: %s', err))
    [ 'Hen Wen' ]
    result = client.query(
      q.map_(q.lambda_("name", q.concat([q.var("name"), "Wen"])), ["Hen "])
    )
    print(result)
    [ "Hen Wen" ]
    try {
      println(Await.result(
        client.query(
      Map(Arr("Hen "), Lambda { name => Concat(Arr(name, "Wen")) })),
        5.seconds
      ))
    } catch {
      case unknown: Throwable => println("Error: " + unknown.getMessage())
    }
    [ "Hen Wen" ]
    Map(
      ['Hen '],
      Lambda('name', Concat([Var('name'), 'Wen'])),
    )
    [ 'Hen Wen' ]
  2. The following query passes multiple arguments to a Lambda. The number of values in the array passed into the Lambda and the number of arguments in the Lambda must match exactly. In this example, the Map passes an array with two elements and the Lambda takes an array with two elements. The Lambda resolves the two arguments to their values and then calls the Concat function with the values.

    try
    {
        Value result = await client.Query(
            Map(
                Arr(Arr("Hen", "Wen")),
                Lambda(Arr("f", "l"), Concat(Arr(Var("f"), Var("l")), " "))
            )
        );
        Console.WriteLine(result);
    }
    catch (Exception e)
    {
        Console.WriteLine($"ERROR: {e.Message}");
    }
    Arr(StringV(Hen Wen))
    result, err := client.Query(
    	f.Map(
    		f.Arr{f.Arr{"Hen", "Wen"}},
    		f.Lambda(
    			f.Arr{"f", "l"},
    			f.Concat(
    				f.Arr{
    					f.Var("f"), f.Var("l"),
    				},
    				f.Separator(" "),
    			))))
    
    if err != nil {
    	fmt.Fprintln(os.Stderr, err)
    } else {
    	fmt.Println(result)
    }
    [Hen Wen]
    System.out.println(
        client.query(
            Map(
                Arr(
                    Arr(Value("Hen"), Value("Wen"))
                ),
                Lambda(
                    Arr(Value("f"),Value("l")),
                    Concat(Arr(Var("f"), Var("l")), Value(" "))
                )
            )
        ).get());
    ["Hen Wen"]
    client.query(
      q.Map(
        [['Hen', 'Wen']],
        q.Lambda(
          ['f', 'l'],
          q.Concat([q.Var('f'), q.Var('l')], ' ')
        ),
      )
    )
    .then((ret) => console.log(ret))
    .catch((err) => console.error('Error: %s', err))
    [ 'Hen Wen' ]
    result = client.query(
      q.map_(
        lambda f, l: q.concat([f, l], " "),
        [["Hen", "Wen"]]
      )
    )
    print(result)
    [ "Hen Wen" ]
    try {
      println(Await.result(
        client.query(
      Map(
        Arr(Arr("Hen", "Wen")),
        Lambda { (f, l) => Concat(Arr(f, l), " ") })),
        5.seconds
      ))
    } catch {
      case unknown: Throwable => println("Error: " + unknown.getMessage())
    }
    [ "Hen Wen" ]
    Map(
      [['Hen', 'Wen']],
      Lambda(
        ['f', 'l'],
        Concat([Var('f'), Var('l')], ' ')
      ),
    )
    [ 'Hen Wen' ]
  3. The following query passes more arguments to the Lambda than are declared. In this case, the _ (underscore) has been provided to the params array so that the Lambda function knows to discard the extra arguments. If the _ had not been provided, this function would have returned an error.

    try
    {
        Value result = await client.Query(
            Map(
                Arr(Arr("Hen", "Wen")),
                Lambda(Arr("f", "_"), Var("f"))
            )
        );
        Console.WriteLine(result);
    }
    catch (Exception e)
    {
        Console.WriteLine($"ERROR: {e.Message}");
    }
    Arr(StringV(Hen))
    result, err :=	client.Query(
    	f.Map(
    		f.Arr{f.Arr{"Hen", "Wen"}},
    		f.Lambda(f.Arr{"f", "_"}, f.Var("f"))))
    
    if err != nil {
    	fmt.Fprintln(os.Stderr, err)
    } else {
    	fmt.Println(result)
    }
    [Hen]
    System.out.println(
        client.query(
            Map(
                Arr(Arr(Value("Hen"), Value("Wen"))),
                Lambda(
                    Arr(Value("f"),Value("_")),
                    Concat(Arr(Var("f")), Value(" "))
                )
            )
        ).get());
    ["Hen"]
    client.query(
      q.Map(
        [['Hen', 'Wen']],
        q.Lambda(['f', '_'], q.Var('f')),
      )
    )
    .then((ret) => console.log(ret))
    .catch((err) => console.error('Error: %s', err))
    [ 'Hen' ]
    result = client.query(
      q.map_(
        q.lambda_(["f", "_"], q.var("f")),
        [["Hen", "Wen"]]
      )
    )
    print(result)
    [ "Hen" ]
    try {
      println(Await.result(
        client.query(
      Map(Arr(Arr("Hen", "Wen")), Lambda { (f, _) => f })),
        5.seconds
      ))
    } catch {
      case unknown: Throwable => println("Error: " + unknown.getMessage())
    }
    [ "Hen" ]
    Map(
      [['Hen', 'Wen']],
      Lambda(['f', '_'], Var('f')),
    )
    [ 'Hen' ]
  4. The following query uses the Map function to provide two objects to the Lambda as the user parameter. The Lambda selects the email field from each object, which becomes part of the response:

    try
    {
        Value result = await client.Query(
            Map(
                Arr(
                    Obj(
                        "name", "Hen Wen",
                        "email", "henwen@black.cauldron"
                    ),
                    Obj(
                        "name", "Taran",
                        "email", "taran@black.cauldron"
                    )
                ),
                Lambda(
                    "user",
                    Select(Arr("email"), Var("user"))
                )
            )
        );
        Console.WriteLine(result);
    }
    catch (Exception e)
    {
        Console.WriteLine($"ERROR: {e.Message}");
    }
    Arr(StringV(henwen@black.cauldron), StringV(taran@black.cauldron))
    result, err := client.Query(
    	f.Map(
    		f.Arr{
    			f.Obj{
    				"name": "Hen Wen",
    				"email": "henwen@black.cauldron",
    			},
    			f.Obj{
    				"name": "Taran",
    				"email": "taran@black.cauldron",
    			},
    		},
    		f.Lambda(
    			"user",
    			f.Select(f.Arr{"email"}, f.Var("user")),
    		),
    	))
    
    
    if err != nil {
    	fmt.Fprintln(os.Stderr, err)
    } else {
    	fmt.Println(result)
    }
    [henwen@black.cauldron taran@black.cauldron]
    System.out.println(
        client.query(
            Map(
                Arr(
                    Obj(
                        "name", Value("Hen Wen"),
                        "email", Value("henwen@black.cauldron")
                    ),
                    Obj(
                        "name", Value("Taran"),
                        "email", Value("taran@black.cauldron")
                    )
                ),
                Lambda(
                    "user",
                    Select(Arr(Value("email")), Var("user"))
                )
            )
    
        ).get());
    ["henwen@black.cauldron", "taran@black.cauldron"]
    client.query(
      q.Map(
        [
          {
            name: 'Hen Wen',
            email: 'henwen@black.cauldron',
          },
          {
            name: 'Taran',
            email: 'taran@black.cauldron',
          },
        ],
        q.Lambda(
          'user',
          q.Select(['email'], q.Var('user'))
        )
      )
    )
    .then((ret) => console.log(ret))
    .catch((err) => console.error('Error: %s', err))
    [ 'henwen@black.cauldron', 'taran@black.cauldron' ]
    result = client.query(
      q.map_(
        q.lambda_(
          "user",
          q.select(["email"], q.var("user"))
        ),
        [
          {
            "name": "Hen Wen",
            "email": "henwen@black.cauldron"
          },
          {
            "name": "Taran",
            "email": "taran@black.cauldron"
          }
        ]
      )
    )
    print(result)
    ['henwen@black.cauldron', 'taran@black.cauldron']
    try {
      println(Await.result(
        client.query(
          Map(
            Arr(
              Obj(
                "name" -> "Hen Wen",
                "email" -> "henwen@black.cauldron"
              ),
              Obj(
                "name" -> "Taran",
                "email" -> "taran@black.cauldron"
              )
            ),
            Lambda(
              "user",
              Select(Arr("email"), Var("user"))
            )
          )
        ),
        5.seconds
      ))
    } catch {
      case unknown: Throwable => println("Error: " + unknown.getMessage())
    }
    ["henwen@black.cauldron", "taran@black.cauldron"]
    Map(
      [
        {
          name: 'Hen Wen',
          email: 'henwen@black.cauldron',
        },
        {
          name: 'Taran',
          email: 'taran@black.cauldron',
        },
      ],
      Lambda(
        'user',
        Select(['email'], Var('user'))
      )
    )
    [ 'henwen@black.cauldron', 'taran@black.cauldron' ]

Was this article helpful?

We're sorry to hear that.
Tell us how we can improve!
Visit Fauna's Discourse forums or email docs@fauna.com

Thank you for your feedback!