Next: , Previous: SRFI-14, Up: SRFI Support

6.4.13 SRFI-16 - case-lambda

The syntactic form case-lambda creates procedures, just like lambda, but has syntactic extensions for writing procedures of varying arity easier.

The syntax of the case-lambda form is defined in the following EBNF grammar.

        --> (case-lambda <case-lambda-clause>)
        --> (<formals> <definition-or-command>*)
        --> (<identifier>*)
          | (<identifier>* . <identifier>)
          | <identifier>

The value returned by a case-lambda form is a procedure which matches the number of actual arguments against the formals in the various clauses, in order. Formals means a formal argument list just like with lambda (see Lambda). The first matching clause is selected, the corresponding values from the actual parameter list are bound to the variable names in the clauses and the body of the clause is evaluated. If no clause matches, an error is signalled.

The following (silly) definition creates a procedure foo which acts differently, depending on the number of actual arguments. If one argument is given, the constant #t is returned, two arguments are added and if more arguments are passed, their product is calculated.

     (define foo (case-lambda
                   ((x) #t)
                   ((x y) (+ x y))
                     (apply * z))))
     (foo 'bar)
     (foo 2 4)
     (foo 3 3 3)

The last expression evaluates to 1 because the last clause is matched, z is bound to the empty list and the following multiplication, applied to zero arguments, yields 1.