Lambda

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

Parameter 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 "),
                Lambda(
                    "name",
                    Concat(Arr(Var("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] %s: %s',
      err.name,
      err.message,
      err.errors()[0].description,
    ))
    [ 'Hen Wen' ]
    result = client.query(
      q.map_(
        q.lambda_(
          "name",
          q.concat([q.var("name"), "Wen"])
        ),
        ["Hen "]
      )
    )
    print(result)
    [ "Hen Wen" ]
    Map(
      ['Hen '],
      Lambda(
        "name",
        Concat([Var("name"), "Wen"])
      ),
    )
    [ 'Hen Wen' ]
    Query metrics:
    •    bytesIn:  88

    •   bytesOut:  24

    • computeOps:   1

    •    readOps:   0

    •   writeOps:   0

    •  readBytes:   0

    • writeBytes:   0

    •  queryTime: 2ms

    •    retries:   0

  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] %s: %s',
      err.name,
      err.message,
      err.errors()[0].description,
    ))
    [ 'Hen Wen' ]
    result = client.query(
      q.map_(
        lambda f, l: q.concat([f, l], " "),
        [["Hen", "Wen"]]
      )
    )
    print(result)
    [ "Hen Wen" ]
    Map(
      [['Hen', 'Wen']],
      Lambda(
        ['f', 'l'],
        Concat([Var('f'), Var('l')], ' ')
      ),
    )
    [ 'Hen Wen' ]
    Query metrics:
    •    bytesIn: 117

    •   bytesOut:  24

    • computeOps:   1

    •    readOps:   0

    •   writeOps:   0

    •  readBytes:   0

    • writeBytes:   0

    •  queryTime: 5ms

    •    retries:   0

  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] %s: %s',
      err.name,
      err.message,
      err.errors()[0].description,
    ))
    [ 'Hen' ]
    result = client.query(
      q.map_(
        q.lambda_(["f", "_"], q.var("f")),
        [["Hen", "Wen"]]
      )
    )
    print(result)
    [ "Hen" ]
    Map(
      [['Hen', 'Wen']],
      Lambda(['f', '_'], Var('f')),
    )
    [ 'Hen' ]
    Query metrics:
    •    bytesIn:  76

    •   bytesOut:  20

    • computeOps:   1

    •    readOps:   0

    •   writeOps:   0

    •  readBytes:   0

    • writeBytes:   0

    •  queryTime: 5ms

    •    retries:   0

  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] %s: %s',
      err.name,
      err.message,
      err.errors()[0].description,
    ))
    [ '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']
    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' ]
    Query metrics:
    •    bytesIn: 211

    •   bytesOut:  61

    • computeOps:   1

    •    readOps:   0

    •   writeOps:   0

    •  readBytes:   0

    • writeBytes:   0

    •  queryTime: 4ms

    •    retries:   0

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!