CS326 Programming Languages, Aug 25 1999
Scheme program:
Sequence of definitions and expressions
executed in order by the scheme system
Top level
Scheme's REPL
Read, eval, print,
Small number of special forms needed.
1. (define var expr)
Needed for binding. Used only at the top level.
2.(if test-exp then-exp else-exp)
Sequence:
1. test-exp is evaluated
2. if true
then-exp is evaluated
if false
else-exp evaluated
This has to be a special form.
Cannot be a procedure
> (if #t 1 2)
> (zero? 5)
> (if (zero? 5) 1 (+ 1 2))
> (define true #t)
> (define false #f)
> (if (if true false true) 2 3)
Why cannot if be a procedure ?
(if (zero? a) 0 (/ x a))
Data types:
1. Set of values of that type
2. Procedures that operate on that type
3. Representation (internal) and printed/read
Type checking
-------------
Scheme: Dynamic type checking (when procedures are INVOKED)
Static type checking (when procedure is compiled)
based only on program text not run-time values
Catches type errors early but more complicated
checking
Numbers, booleans, characters, strings, symbols.
> (eq? (boolean? #f) (not #f))
#t
> (number? 5)
#t
> (= 5 5)
#t
> (not (= 5 5))
#f
> (char? #\$)
#t
#\a #\t #\space #\newline
> (char=? #\a #\b)
#f
> (char->integer #\a)
97
char->alphabetic?
char->numeric?
char->whitespace? (space, linefeed, return)
> (string? "this is a string")
#t
string-length
string-append
string->symbol
(string->symbol "count")
string->number
string->list
> (string #\a #\b)
"ab"
> (define s "this is a.")
> (string-ref s 2)
#\i
SYMBOLS:
When identifiers are treated as values in scheme
they are called SYMBOLS
Special form to create symbols
> (quote datum)
> 'datum
The only literals that are self quoting are
numbers, booleans, strings, and characters.
> (define x 3)
> (number? x)
#t
> (symbol? x)
#f
> (symbol? 'x)
#t
> (eq? 'x 'y)
#f
> (define y 'apple)
> (eq? y (quote apple))
#t
> (eq? y 'y)
LISTS
------
Ordered sequence of elements, which may be
of arbitrary types.
(list arguments) ==> a list
> (list 1 2 3)
(1 2 3)
> (list)
()
(cons scheme-value list) => a list
> (cons 'a '(c d))
(a c d)
> (list 'a '(c d))
(a (c d))
> (cons '(a b) '(c d))
((a b) c d)
> (list '(a b) '(c d))
((a b) (c d))
> (append '(a b) '(c d))
(a b c d)
> (append '() '(c d))
(c d)
> (append '(a b) '())
(a b)
CAR and CDR
(car (cons v l)) = v
(cdr (cons v l)) = l
> (cadr '(a b c))
b
> (cddr '(a b c))
(c)
> (caddr '(a b c))
c
> (null? '())
#t
PAIRS
(a (b c) d)
(a . ((b . (c . ())) . (d . ())))
((1) 2 3 . 4)
((1 . ()) . (2 . (3 . 4)))
Symbols, pairs, and eq?
> (define a (cons 3 '()))
> (define b (cons 3. ()))
> (eq? a b)
#f
> (eq? (cons 1 2) (cons 1 2))
#f
> (eq? '(3) '(3))
undefined
(define x1 '(a b))
(define x2 '(a))
(define x3 (cons x1 x2))
> (load "wk1.2.ss")
> (eq? x3 (cons x1 x2))
> (eq? (cdr x3) x2)
> (eq? (car x1) (car x2))
> (cons (cons 'a 'b) (cons 'c '()))
> (cons 1 (cons 2 3))
>
LAMBDA
(lambda formals body)
Sushil Louis
Last modified: Wed Aug 25 15:38:21 PDT 1999