Naming is the first abstraction
A program that only computes (* 3.14159 (* 2 2)) is a calculator. Programming begins when you can give a computation a name and reuse it: "the area of a circle of radius r". Once named, the computation becomes a building block for bigger ones, and you can stop thinking about how it works and think about what it does.
Scheme gives you exactly one tool for this: the procedure, created by lambda and usually named with define. There is no separate syntax for functions, methods, constructors or static members. A procedure is a value like a number or a string; it can be stored, passed and returned. This lesson shows how to make procedures, how to make decisions inside them, and how to introduce local names, and it introduces lexical scope, the rule that decides which binding a name refers to. Lexical scope was one of Scheme's founding ideas, and nearly every modern language now follows it.
define and lambda
Definition— lambda
(lambda (param ...) body ...) creates a procedure. When the procedure is called, its parameters are bound to the arguments, the body expressions are evaluated in order, and the value of the last one is returned. The name comes from Alonzo Church's lambda calculus, the 1930s mathematical theory of functions that Scheme was designed to reflect.
Definition— define
(define name expression) binds name to the value of expression. The form (define (name param ...) body ...) is shorthand for (define name (lambda (param ...) body ...)).
Definition— Variadic procedure
A procedure that accepts a variable number of arguments. In the parameter list, a dot before the last name, (lambda (a b . rest) ...), collects any extra arguments into a list; a bare name instead of a list, (lambda args ...), collects all of them.
(import (scheme base) (scheme write) (scheme inexact) (scheme case-lambda))
(define (square x) (* x x))
(define hypotenuse
(lambda (a b)
(sqrt (+ (square a) (square b)))))
(define (average . numbers)
(/ (apply + numbers) (length numbers)))
(define (greet name . titles)
(if (null? titles)
(string-append "Hello, " name)
(string-append "Hello, " (car titles) " " name)))
(define area
(case-lambda
((side) (* side side))
((width height) (* width height))))
(write (square 12)) (newline)
(write (hypotenuse 3 4)) (newline)
(write ((lambda (x y) (- x y)) 10 3)) (newline)
(write (average 4 8 15 16 23 42)) (newline)
(write (greet "Wanjiru")) (newline)
(write (greet "Okoye" "Dr.")) (newline)
(write (list (area 5) (area 3 4))) (newline)144
5
7
18
"Hello, Wanjiru"
"Hello, Dr. Okoye"
(25 12)squareuses the shorthand;hypotenusespells out thelambda. They are the same kind of definition. Because(sqrt 25)is a perfect square, Chibi returns the exact integer 5.((lambda (x y) (- x y)) 10 3)creates a procedure and calls it immediately, without ever naming it. The operator position of a call can hold any expression that evaluates to a procedure.averagecollects all its arguments into the listnumbers.applycalls a procedure with the elements of a list as arguments. The result, 108/6, is the exact integer 18.greethas one required parameter and an optional rest list;(car titles)takes its first element (lesson 4 covers lists properly). This is the R7RS idiom for optional arguments.case-lambda, from(scheme case-lambda), makes a procedure that picks a body according to how many arguments it receives.
Example— From a formula to a procedure
Money left at an interest rate per year for years grows to . As a procedure:
(define (compound principal rate years)
(* principal (expt (+ 1 rate) years)))
(compound 1000 1/20 2) ; => 2205/2
(compound 1000 0.05 2) ; => 1102.5
(compound 1000 1/20 10) ; => 16679880978201/10240000000
(compound 1000 0.05 10) ; => 1628.894626777442The definition is a direct transcription of the formula, with three named parameters instead of single letters. Try it at the REPL with a few inputs before using it anywhere else; this habit of testing each small procedure as soon as it exists is the heart of working in Scheme.
The two kinds of number give two kinds of answer. With an exact rate of 1/20 (five percent written as a fraction), Scheme computes the exact value: after ten years, a fraction with a very large numerator and denominator, correct to the last digit. With the inexact 0.05, it computes a floating-point approximation, which is what you want for display but which carries tiny rounding errors that accumulate over many steps. Financial software often keeps amounts exact (or as integer cents) and converts to a decimal only when printing. Scheme lets you choose per calculation, simply by how you write the inputs.
Making decisions
(import (scheme base) (scheme write))
(define (leap-year? year)
(and (= 0 (modulo year 4))
(or (not (= 0 (modulo year 100)))
(= 0 (modulo year 400)))))
(define (days-in-month month year)
(case month
((april june september november) 30)
((february) (if (leap-year? year) 29 28))
(else 31)))
(define (describe-temperature c)
(cond ((< c 0) "freezing")
((< c 15) "cool")
((< c 25) "pleasant")
(else "hot")))
(for-each (lambda (y) (write (list y (leap-year? y))) (newline))
'(1900 2000 2024 2026))
(write (map (lambda (m) (days-in-month m 2024)) '(january february april))) (newline)
(write (map describe-temperature '(-5 10 20 31))) (newline)
(write (list (and 1 2 3) (and 1 #f 3) (or #f 7 8) (or #f #f))) (newline)
(write (cond ((assv 2 '((1 . one) (2 . two))) => cdr) (else 'none))) (newline)
(when (> 3 2)
(display "when runs its body in order")
(newline))
(unless (> 3 2)
(display "this never prints")
(newline))(1900 #f)
(2000 #t)
(2024 #t)
(2026 #f)
(31 29 30)
("freezing" "cool" "pleasant" "hot")
(3 #f 7 #f)
two
when runs its body in order| Form | Behaviour |
|---|---|
(if test then else) | evaluate test; then exactly one branch. Without else, the value when the test fails is unspecified. |
(cond (test expr ...) ... (else expr ...)) | try each clause's test in order; evaluate the first clause whose test is true |
(case key ((datum ...) expr ...) ... (else ...)) | compare key with literal data using eqv?; good for symbols, characters and small integers |
(and e ...) | evaluate left to right; stop at the first #f; otherwise return the last value |
(or e ...) | evaluate left to right; return the first true value, or #f |
(when test body ...), (unless test body ...) | run several expressions for their effects if the test is true (or false) |
Two details deserve attention. and and or return values, not just #t or #f: (or #f 7 8) is 7, and (and 1 2 3) is 3. This makes or handy for defaults, as in (or user-choice 'english). And a cond clause written (test => procedure) passes the test's value to the procedure. assv (lesson 6) returns the pair (2 . two) or #f; when it finds something, cdr extracts the two.
The leap-year rule reads almost like its English statement: divisible by 4, and either not divisible by 100 or divisible by 400. That is why 1900 is not a leap year and 2000 is.
let forms and lexical scope
define at the top level creates global names. Inside a procedure you usually want local names that exist only for a while. Scheme has several forms for this, all of which are, at heart, sugar for calling a lambda.
(import (scheme base) (scheme write))
(define x 10)
(define (show-x) x)
(let ((x 1)
(y x))
(write (list 'let x y)) (newline))
(let* ((x 1)
(y x))
(write (list 'let* x y)) (newline))
(let ((x 99))
(write (list 'inside x 'show-x (show-x))) (newline))
(letrec ((my-even? (lambda (n) (if (= n 0) #t (my-odd? (- n 1)))))
(my-odd? (lambda (n) (if (= n 0) #f (my-even? (- n 1))))))
(write (list (my-even? 10) (my-odd? 7))) (newline))
(define (price-with-tax price rate)
(define tax (* price rate))
(define (round-cents amount) (/ (round (* amount 100)) 100))
(round-cents (+ price tax)))
(write (price-with-tax 19.99 0.16)) (newline)
(write (price-with-tax 50 3/20)) (newline)
(let-values (((q r) (floor/ 17 5)))
(write (list 'quotient q 'remainder r)) (newline))(let 1 10)
(let* 1 1)
(inside 99 show-x 10)
(#t #t)
23.19
115/2
(quotient 3 remainder 2)Each line repays careful reading.
letevaluates all its initial values first, in the surrounding scope, and only then binds the names. So in(let ((x 1) (y x)) ...), thexused to initialiseyis the globalx, 10. In fact(let ((x 1) (y x)) body)means exactly((lambda (x y) body) 1 x).let*binds one name at a time, so each initial value can see the names before it:ygets the newx, 1.- Lexical scope. Inside
(let ((x 99)) ...), the namexmeans 99. Butshow-xstill returns 10. A procedure's free variables are looked up where the procedure was written, not where it is called.show-xwas defined at the top level, wherexis 10, and no laterletcan change what itsxrefers to. letrecmakes all its names visible to all its initial values, so the procedures can call each other. Mutual recursion likemy-even?andmy-odd?needs it.- Internal definitions. A
defineat the start of a procedure body creates a local name, equivalent to aletrec*.price-with-taxdefines a localtaxand a local helper procedure. Most Scheme programmers prefer internal definitions to deeply nestedlets for helpers. - Exactness flows through. With an inexact price the result is the float
23.19; with exact inputs,50and3/20, the answer is the exact115/2, that is 57.50 with no rounding error at all. let-valuesbinds several results from a procedure that returns multiple values;floor/returns both the quotient and the remainder.
The figure shows the environment model: every procedure carries a reference to the environment where it was created, and looking up a name means searching the current frame and then each parent in turn. That simple rule is lexical scope, and it is what makes closures (lesson 5) work.
How Scheme code is written
Scheme style is consistent across implementations and decades, and following it makes your code readable to everyone in the community.
- Names are lowercase words joined by hyphens:
days-in-month. Predicates end in?(leap-year?,null?), procedures that mutate end in!(set!,vector-set!), and conversions use an arrow (string->symbol,list->vector). - Indentation carries the structure. The body of a
define,letorlambdais indented two spaces; the arguments of a call line up under the first argument. Closing parentheses pile up at the end of the last line, never on lines of their own. - Comments:
;for a comment at the end of a line,;;for a comment on its own line,#| ... |#for a block, and#;to comment out the next whole expression, which is handy while experimenting. - Small procedures. Scheme rewards breaking a problem into many small, named procedures, each easy to test at the REPL. A procedure longer than a screen is a sign that some part of it deserves a name.
- Prefer
letand internaldefineto global variables. Keeping names local makes it obvious which code can see and depend on them.
An editor that understands parentheses (highlighting matching pairs, re-indenting on demand, and ideally structural editing) is essential. Emacs with Geiser, DrRacket, and Lisp extensions for VS Code and Vim all provide this.
Common mistakes
Misconception
Expecting let to see its own earlier bindings. (let ((a 1) (b (+ a 1))) b) does not use the new a; it refers to whatever a is outside (or fails if there is none). Use let* when a binding depends on an earlier one.
Misconception
Thinking scope is decided at call time. In a few old Lisps and in shell scripts, a procedure's free variables were looked up in the caller's environment (dynamic scope). Scheme uses lexical scope: the defining environment wins, as show-x showed. Dynamic scope is still available deliberately, through parameter objects (make-parameter and parameterize), for settings such as the current output port.
Misconception
Using if with several expressions in a branch. (if test (display "a") (newline) (display "b")) is a syntax error: if takes at most three subexpressions. Group expressions with begin, or use when and cond, whose clauses allow several expressions.
Misconception
Expecting and and or to return booleans. They return one of their operands' values. (or (assv key table) 'missing) relies on this.
Exercises
1. Expressions, define, lambda and lexical scope
CoreComputationalWhat is the value of this expression?
(let ((x 2) (y 3))
(let ((x 7)
(z (+ x y)))
(* z x)))
2. Expressions, define, lambda and lexical scope
CoreComputationalNow the inner form is let*. What is the value?
(let ((x 2) (y 3))
(let* ((x 7)
(z (+ x y)))
(* z x)))
3. Expressions, define, lambda and lexical scope
CoreComputationalWhat does this print?
(write (list (or #f '() 3) (and 'a 'b)))
4. Expressions, define, lambda and lexical scope
CoreComputationalWhat does (f 5) return?
(define n 1)
(define (get-n) n)
(define (f n) (get-n))
5. Expressions, define, lambda and lexical scope
Warm-upComputationalWhat does (sum) return?
(define (sum . xs) (apply + xs))
6. Expressions, define, lambda and lexical scope
Warm-upComputationalWhat is the value of this expression?
(case (* 2 3)
((2 3 5 7) 'prime)
((1 4 6 8 9) 'composite)
(else 'other))
7. Expressions, define, lambda and lexical scope
Warm-upHumanWhich definition is exactly equivalent to (define (double x) (* 2 x))?
8. Expressions, define, lambda and lexical scope
CoreComputationalUsing the lesson's leap-year? and days-in-month, what does (days-in-month 'february 1900) return?
Further reading and resources
- R7RS-small, section 4: ExpressionsThe definitive description of lambda, if, cond, case, let and the other expression types.
- Scheme documentationCommunity-maintained guides and references.
- Structure and Interpretation of Computer Programs, chapter 1 · Harold Abelson and Gerald Jay Sussman with Julie SussmanThe classic treatment of procedures as abstractions.