next up previous contents index
Next: Binding Up: Introductory Scheme Previous: Math Operations

Defining Functions

 

The define  function  is used to define functions. For format of define is:

 
		 (define (name args) body)

Where args is a list of arguments arg1 arg2 ... argN, and body is the body of the function. When the function is called, via (name arg1 arg2 ... argN), the actual arguments in the call are bound to the formal arguments in the define, which act as local variables within body. For example, the ever-popular factorial  function would be defined as follows (n factorial is equal to tex2html_wrap_inline1152 , and 0 factorial is defined to equal 1):
   (define (fact n)
      (cond
         ((= n 0) 1)
         (else (* n (fact (- n 1))))))
A call to this function with n equal to 3 proceeds as follows:
 
(fact 3)

tex2html_wrap_inline972 (* 3 (fact 2))

tex2html_wrap_inline972 (* 3 (* 2 (fact 1)))

tex2html_wrap_inline972 (* 3 (* 2 (* 1 (fact 0))))

tex2html_wrap_inline972 (* 3 (* 2 (* 1 1)))

tex2html_wrap_inline972 6

A function with a variable number of arguments  is defined as follows:
 
		 (define (name args . rest) body)

Within body, the arguments arg1 arg2 ... argN are bound to the first N arguments to the function, and any remaining arguments are bound as a list to rest.



Steven J. Zeil
Tue Mar 4 14:36:27 EST 1997