[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4.3 Making Procedures

Special Form: lambda formals body ...
[R5RS] Evaluates to a procedure. The environment in effect when this expression is evaluated is stored in the procedure. When the procedure is called, body is evaluated sequentially in the stored environment extended by the bindings of the formal arguments, and returns the value(s) of the last expression in the body.

Formals should have one of the following forms:

 
(lambda (a b) (+ a b))
  => procedure that adds two arguments

((lambda (a b) (+ a b)) 1 2)
  => 3

Note: Some Scheme implementations extend the syntax of formals to have notation of optional arguments or keyword arguments, similar to CommonLisp's. Gauche doesn't have such extensions now.

Macro: cut expr-or-slot expr-or-slot2 ...
Macro: cute expr-or-slot expr-or-slot2 ...
[SRFI-26] Convenience macros to notate a procedure compactly. This form can be used to realize partial application, a.k.a sectioning or projection.

Each expr-or-slot must be either an expression or a symbol <>, indicating a 'slot'. The last expr-or-slot can be a symbol <...>, indicating a 'rest-slot'. Cut expands into a lambda form that takes as many arguments as the number of slots in the given form, and whose body is an expression
 
  (expr-or-slot expr-or-slot2 ...)
where each occurrence of <> is replaced to the corresponding argument. In case there is a rest-slot symbol, the resulting procedure is also of variable arity, and all the extra arguments are passed to the call of expr-or-slot. See the fourth example below.

 
(cut cons (+ a 1) <>)  == (lambda (x2) (cons (+ a 1) x2))
(cut list 1 <> 3 <> 5) == (lambda (x2 x4) (list 1 x2 3 x4 5))
(cut list)             == (lambda () (list))
(cut list 1 <> 3 <...>)
   == (lambda (x2 . xs) (apply list 1 x2 3 xs))
(cut <> a b)           == (lambda (f) (f a b))

;; Usage
(map (cut * 2 <>) '(1 2 3 4))
(for-each (cut write <> port) exprs)

Cute is a variation of cut that evaluates expr-or-slots before creating the procedure.

 
(cute cons (+ a 1) <>)
   == (let ((xa (+ a 1))) (lambda (x2 (cons xa x2))))

Gauche also has a built-in procedure pa$ for partial application (See section 6.15.1.2 Combinators).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

This document was generated by Ken Dickey on November, 28 2002 using texi2html