apply
Apply an anonymous function (lambda expression).
Syntax
tcl
apply lambdaExpr ?arg ...?Parameters
- lambdaExpr: A list containing
{params body ?namespace?}- params: Parameter list (same format as
proc)- Required parameters: Simple names that must have values provided
- Optional parameters with defaults: Parameters specified as
{name default}pairs - Variadic args: The special
argsparameter as the last parameter collects remaining arguments into a list
- body: The script to execute
- namespace: Optional namespace context for the lambda (relative to global namespace)
- params: Parameter list (same format as
- arg ...: Arguments to pass to the lambda
Returns
The result of evaluating body with args bound to params.
Parameter Behavior
Arguments with default values that are followed by non-defaulted arguments become required arguments. Enough actual arguments must be supplied to allow all arguments up to and including the last required formal argument.
tcl
apply { {{x 1} y} {list $x $y} } 10 ;# Error: wrong # args
apply { {{x 1} y} {list $x $y} } 5 10 ;# Returns "5 10"Note: The args parameter does NOT make preceding optionals required:
tcl
apply { {{x 1} args} {list $x $args} } ;# Returns "1 {}"
apply { {{x 1} args} {list $x $args} } 10 ;# Returns "10 {}"Examples
Basic lambda
Output
Lambda with multiple parameters
Output
Inline lambda
Output
Lambda with default parameters
Output
Using lambdas with higher-order functions
Output
Variadic args parameter
Output
