Procedures

Procedures

Robbert Haarman

2010-12-11


Introduction

Procedures are first-class objects in Scheme. This means that they can be treated as values and passed as arguments to other procedures, or returned from procedures. Defining procedures (other than implicitly with define) is done using lambda.


Operations on Symbols

; Create a procedure that returns its argument
(lambda (foo) foo)	; #

; The following function creates a procedure that adds n
; to its argument when called
(define (make-addn n)
	(lambda (x) (+ x n)))

(define add5 (make-addn 5))
(add5 4)	; 9

; Test if something is a procedure
(procedure? add5)	; #t
(proceduce? (lambda (x) (not x)))	; #t
(procedure? display)	; #t

; Apply a procedure to each element in a list
(foreach display '(1 2 3))	; displays "123"
(foreach (lambda (x)
	(display x)
	(display #\space)) '(1 2 3))	; displays "1 2 3"

; Transform a list through some mapping function
(map (lambda (n) (* n n)) '(1 2 3))	; (1 4 9)
Valid XHTML 1.1! Valid CSS! Viewable with Any Browser