Skip to content

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 args parameter 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)
  • 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

See Also

  • proc - Define named procedures
  • return - Return from procedure
  • global - Access global variables from within lambda
  • upvar - Access variables in calling frames
  • variable - Access namespace variables
  • namespace - Namespace operations