Next: , Previous: , Up: scheme overview   [Index]


3.1.8 Procedures

Definitions can also be used to define procedures:

(define (f x)
  (+ x 42))

(f 23) ⇒ 65

A procedure is, slightly simplified, an abstraction of an expression over objects. In the example, the first definition defines a procedure called f. (Note the parentheses around f x, which indicate that this is a procedure definition.) The expression (f 23) is a procedure call, meaning, roughly, “evaluate (+ x 42) (the body of the procedure) with ‘x’ bound to ‘23’”.

As procedures are objects, they can be passed to other procedures:

(define (f x)
  (+ x 42))

(define (g p x)
  (p x))

(g f 23) ⇒ 65

In this example, the body of g is evaluated with p bound to f and ‘x’ bound to ‘23’, which is equivalent to (f 23), which evaluates to ‘65’.

In fact, many predefined operations of Scheme are provided not by syntax, but by variables whose values are procedures. The + operation, for example, which receives special syntactic treatment in many other languages, is just a regular identifier in Scheme, bound to a procedure that adds number objects. The same holds for * and many others:

(define (h op x y)
  (op x y))

(h + 23 42) ⇒ 65
(h * 23 42) ⇒ 966

Procedure definitions are not the only way to create procedures. A lambda expression creates a new procedure as an object, with no need to specify a name:

((lambda (x) (+ x 42)) 23) ⇒ 65

The entire expression in this example is a procedure call; (lambda (x) (+ x 42)), evaluates to a procedure that takes a single number object and adds 42 to it.


Next: , Previous: , Up: scheme overview   [Index]