Scheme in Depth

17.1 Philosophy and Standards

Scheme (Guy Steele and Gerald Sussman, MIT, 1975) is a minimalist Lisp: lexical scope, first-class continuations, guaranteed tail calls, hygienic macros, and a tiny core.

Standards: R4RS, R5RS (1998, classic), R6RS (2007, larger), R7RS-small (2013, current), with R7RS-large in progress. SRFIs (Scheme Requests for Implementation) add libraries (lists SRFI-1, strings SRFI-13, hash tables SRFI-69/125, records SRFI-9).

Implementations: Chez Scheme (very fast; Racket's backend), Guile (GNU's extension language), Chicken (compiles to C), Gambit, Chibi (small R7RS), Gauche, MIT/GNU Scheme (SICP's home), Kawa (JVM), Cyclone.

17.2 R7RS Essentials

(import (scheme base) (scheme write) (scheme char))   ; R7RS libraries

(define-record-type point                  ; records (R7RS / SRFI-9)
  (make-point x y)
  point?
  (x point-x set-point-x!)
  (y point-y))
(define p (make-point 3 4))
(point-x p)                                ; 3

(define v (vector 1 2 3))                  ; vectors: O(1) access
(vector-ref v 0)                           ; 1
(vector-set! v 0 99)

(define-values (q r) (floor/ 7 2))         ; multiple values
(call-with-values (lambda () (values 1 2)) +)   ; 3

(guard (e (#t (display "caught: ") (display (condition/report-string e))))   ; error handling (R7RS guard)
  (error "something bad" 42))
;; Portable version: (guard (e ((error-object? e) (display (error-object-message e)))) ...)

(define-library (mylib math)               ; defining a library
  (export square cube)
  (import (scheme base))
  (begin
    (define (square x) (* x x))
    (define (cube x) (* x x x))))

(string-map char-upcase "scheme")          ; "SCHEME"
(let-values (((a b) (values 1 2))) (+ a b))  ; 3
(case-lambda ((x) x) ((x y) (+ x y)))      ; multi-arity procedures
(delay (+ 1 2)) (force (delay (+ 1 2)))    ; promises (lazy evaluation)
(dy
…

17.3 Scheme Idioms

Use named let for loops, tail recursion for iteration, define inside bodies for helper functions, association lists for small maps, and higher-order functions everywhere.

SICP (*Structure and Interpretation of Computer Programs*) is written in Scheme and is the classic companion to this part of the course.