![]() |
![]() |
|
home—info—lectures—exams—archive
Challenge: Write factorial, in Scheme. Soln: ; ! : (-> natural-number natural-number) (define (! n) (if (= n 0) 1 (* n (! (- n 1))))) Btw, I tend to use the primitives "zero?" and "sub1", and will also use this as an excuse to introduce "cond" (Cf "if-else-if"): (define (! n) (cond [(zero? n) 1] [else (* n (! (sub1 n)))]))
Let's go back to the Law of Scheme: An expression is...
Kind of expression | Examples | How to evaluate |
---|---|---|
Value | 17, true, 'arugula | You have the value already. |
Placeholder | pi, + | Get its defined value. |
Function application | Evaluate the subexpressions
|
|
Special form |
|
various, but not shocking |
Note anything interesting? The definition of an expression is recursive, and the rules of how to evaluate an expression are likewise recursive. It's not a coincidence! — recursive data is naturally handled by recursive code.
Speaking of writing code: If you wanted, you could write your own Scheme interpreter: You'd make your own data definitions to represent (your versions of) numbers, placeholders, function-call, and define; then you could write a function which takes in such a data-struct (and a list of define'd placeholders), and returns a value. This is the core of drscheme -- yourself! After seeing mutually-recursive data structures, this is a reasonable week-6 beginner scheme homework (book exercises 14.4.1–4 and 17.7.1–4). Elegance speaks for itself!
Note: A thorough intro-to-programming might teach just three other special forms in Scheme (local, set-struct-field!, set!). (The formal definition of the corresponding part of C++ or Java requires about dense 30 pages, instead of 1. Those specifications have also been found to contain inconsistencies and errors, which have taken a long time to get revised.)
Aggregate data
; Data definition: ; A boa is: ; (make-boa string number) (define-struct boa (name length)) ; name: string? ; length: positive? ; Creates a struct 'boa', along with: ; constructor: make-boa ; accessors: boa-name, boa-length ; predicate: boa? ; mutators: set-boa-name!, set-boa-length! [DISALLOWED for this course.] (define (can-fit? a-boa carrier-len) (<= (boa-length a-boa) carrier-len))
1
We need to be careful here:
When replacing every t
in (define (celc->fahr t) (+ (* 9/5 t) 32)) it's
easy. But what about the technically-correct expression
home—info—lectures—exams—archive
©2008, Ian Barland, Radford University Last modified 2008.Sep.13 (Sat) |
Please mail any suggestions (incl. typos, broken links) to ibarland ![]() |
![]() |