Values can be named using the define special form:
(define pi 3.14)(* pi 2)
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 <name> is a symbol to be associated with the procedure definition in the environment. The <formal parameters> are the names used within the body of the procedure to refer to the corresponding arguments of the procedure. The <body> is an expression that will yield the value of the procedure application when the formal parameters are replaced by the actual arguments to which the procedure is applied. The <name> and the <formal parameters> are grouped within parentheses, just as they would be in an actual call to the procedure being defined.
Having defined square, we can now use it in call expressions:
(square 21)
(square (+ 2 5))
(square (square 3))
User-defined functions can take multiple arguments and include special forms:
(define (average x y)(/ (+ x y) 2))
(average 1 3)
(define (abs x)(if (< x 0)(- x)x))
(abs -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)
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)