Quoting in Scheme

Andy Balaam

Contents

Data made from code

> (list "a" "b" "c")
("a" "b" "c")
> (list a b c)
reference to undefined identifier: a
> (list 'a 'b 'c)
(a b c)

Data made from code (2)

> (list 'a (list 'b1 'b2) 'c)
(a (b1 b2) c)
> '(a (b1 b2) c)
(a (b1 b2) c)
> 'a
a
> a
reference to undefined identifier: a

Side note: the empty list

> ()
missing procedure expression
> (list)
()
> '()
()
> null
()
> 'null
null

Asking about data

> (define z 1)

> (symbol? 'z)
#t
> (symbol? z)
#f
> (number? 'z)
#f
> (number? z)
#t

Treating data as code

> (define forty-two '(* 6 9))

> forty-two
(* 6 9)
> (eval forty-two)
54

Example: generic type safety


(define (safe-sum x y)
    (if (and (integer? x) (integer? y))
        (+ x y)
        "INCORRECT TYPES"))

> (safe-sum 1 2)
3
> (safe-sum 1.1 2.4)
"INCORRECT TYPES"

Example: generic type safety (2)


(define (nonint? x)
    (and (real? x) (not (integer? x))))

(define (safe-sum x y)
    (if (and (nonint? x) (nonint? y))
        (+ x y)
        "INCORRECT TYPES"))

> (safe-sum 1 2)
"INCORRECT TYPES"
> (safe-sum 1.1 2.4)
3.5

Example: generic type safety (3)

(define (replace lst find repl)
    (if (pair? lst)
        (cons
            (replace (car lst) find repl)
            (replace (cdr lst) find repl))
        (if (equal? find lst)
            repl
            lst)))

> (replace '(1 2 3) '2 "XXX")
(1 "XXX" 3)
> (replace '(a (b1 b2) c) 'b1 'BOO)
(a (BOO b2) c)

Example: generic type safety (4)




(define generic-safe-sum
    '(define (safe-sum x y)
        (if (and (TEST x) (TEST y))
            (+ x y)
            "INCORRECT TYPES")))

Example: generic type safety (5)

> generic-safe-sum
(define (safe-sum x y)
    (if (and (TEST x) (TEST y))
        (+ x y)
        "INCORRECT TYPES"))
> (define safe-sum-q
    (replace generic-safe-sum 'TEST 'integer?))

> safe-sum-q
(define (safe-sum x y)
    (if (and (integer? x) (integer? y))
        (+ x y)
        "INCORRECT TYPES"))

Example: generic type safety (6)

> (eval safe-sum-q)

> (safe-sum 1 2)
3
> (safe-sum 1.1 2.4)
"INCORRECT TYPES"

Discussion