[previous] [up] [next]     [index]
Next: Basic Data Extensions Up: Basic Syntax Extensions Previous: Syntax Expansion and Internal

Case-Lambda

The case-lambda form creates a procedure that dispatches to a particular body of expressions based on the number of arguments it receives. This provides a mechanism for creating variable-arity procedures with more control and efficiency than using a ``rest arg'' -- e.g., the x in (lambda (a . x) ...) -- with a lambda expression.

A case-lambda expression has the form:

  (case-lambda
    (formals expr  tex2html_wrap_inline100183 )
     tex2html_wrap_inline100181 )

formals is one of: variable (variable tex2html_wrap_inline100181 ) (variable tex2html_wrap_inline100181 . identifier)

Each (formals expr tex2html_wrap_inline100183 ) clause of a case-lambda expression is analogous to a lambda expression of the form (lambda formals expr tex2html_wrap_inline100183 ). The scope of the variables in each clause's formals includes only the same clause's exprs. The formals variables are bound to actual arguments in an application in the same way that lambda variables are bound in an application.

When a case-lambda procedure is invoked, one clause is selected and its exprs are evaluated for the application; the result of the last expr in the clause is the result of the application. The clause that is selected for an application is the first one with a formals specification that can accommodate the number of arguments in the application.[footnote]

Examples:

  (define f
     (case-lambda
        [(x) x]
        [(x y) (+ x y)]
        [(a . any) a]))
  (f 1) ; => 1
  (f 1 2) ; => 3
  (f 4 5 6 7) ; => 4
  (f) ; raises exn:application:arity 

The result of a case-lambda expression is a regular procedure. Thus, the procedure? predicate returns #t when applied to the result of a case-lambda expression.



PLT