Lambda Expressions
Lambdas are anonymous functions used as arguments to higher-order standard library functions such as Map, Where, Reduce, Find, All, Any, SortBy, and Each.
Syntax
x => x * 2 # Single parameter
(x, y) => x + y # Multiple parameters
(acc, item) => acc + item.price # Used with Reduce
Parentheses around the parameter list are optional for single-parameter lambdas. They are required for multiple parameters.
Single-Expression Body
The body of a lambda is a single expression - not a block of statements. The value of the expression is implicitly returned.
# Valid - single expression
var doubled = Map(Data.numbers, x => x * 2)
# NOT valid - blocks are not supported in lambdas
# var doubled = Map(Data.numbers, x => { var result = x * 2; return result })
Closures
Lambdas capture variables from the enclosing scope:
var threshold = 100
var big = Where(Data.items, x => x > threshold) # Captures 'threshold'
Common Patterns
# Transform
var doubled = Map(Data.numbers, x => x * 2)
var upper = Map(Data.names, n => ToUpper(n))
# Filter
var adults = Where(Data.users, u => u.age >= 18)
var evens = Where(Data.numbers, x => x % 2 == 0)
# Aggregate
var total = Reduce(Data.items, (sum, item) => sum + item.price, 0)
# Search
var first = Find(Data.items, x => x.status == "pending")
# Check
var anyExpired = Any(Data.items, x => x.expired)
var allValid = All(Data.items, x => x.price > 0)
# Sort by computed key
var byPrice = SortBy(Data.items, x => x.price)
Lambda vs Query Functions
For simple single-field comparisons, prefer the query functions (WhereByField, FindByField, etc.) - they are more concise. For complex conditions involving multiple fields or computed values, use lambdas.
# Simple field comparison - prefer query
var active = WhereByField(Data.users, "active", "==", true)
# Complex condition - prefer lambda
var eligible = Where(Data.users, u => u.age >= 18 and u.active and u.balance > 0)