Values can be named using the define special form:
(define pi 3.14)
(* pi 2)
6.28
New functions (called procedures in Scheme) can be defined using a second version of the define special form. For example, to define squaring, we write:
(define (square x) (* x x))
The general form of a procedure definition is:
(define (<name> <formal parameters>) <body>)
The
Having defined square, we can now use it in call expressions:
(square 21)
441
(square (+ 2 5))
49
(square (square 3))
81
User-defined functions can take multiple arguments and include special forms:
(define (average x y)
(/ (+ x y) 2))
(average 1 3)
2
(define (abs x)
(if (< x 0)
(- x)
x))
(abs -3)
3
Scheme supports local definitions with the same lexical scoping rules as Python. Below, we define an iterative procedure for computing square roots using nested definitions and recursion:
(define (sqrt x)
(define (good-enough? guess)
(< (abs (- (square guess) x)) 0.001))
(define (improve guess)
(average guess (/ x guess)))
(define (sqrt-iter guess)
(if (good-enough? guess)
guess
(sqrt-iter (improve guess))))
(sqrt-iter 1.0))
(sqrt 9)
3.00009155413138
Anonymous functions are created using the lambda special form. Lambda is used to create procedures in the same way as define, except that no name is specified for the procedure:
(lambda (<formal-parameters>) <body>)
The resulting procedure is just as much a procedure as one that is created using define. The only difference is that it has not been associated with any name in the environment. In fact, the following expressions are equivalent:
(define (plus4 x) (+ x 4))
(define plus4 (lambda (x) (+ x 4)))
Like any expression that has a procedure as its value, a lambda expression can be used as the operator in a call expression:
((lambda (x y z) (+ x y (square z))) 1 2 3)
12