Lecture 19: Scheme I
Catherine Han & Matthew Jeng
07/24/2017
Interpreters
Goals for the week:
Introduction
Data
Mutability
Objects
Interpreters
Paradigms
Applications
Functions
Scheme
What is Scheme?
- Alan Kay (co-creator of OOP) on Lisp
Scheme Basics
scm> (+ 1 2)
3
scm> (quotient (+ 5 5) (- 4 1))
3
scm> (+ (* 2 8)
(* 3
(+ (+ 1 2)
(+ 3 8))))
58
>>> 1 + 2
3
>>> (5 + 5) // (4 - 1)
3
>>> (2 * 8) + (3 * ((1 + 2) + (3 + 8)))
58
Special Forms
Not your average Scheme expression
An expression that follows special evaluation rules; they are evaluated differently from call expressions
Include: assignment expressions, quoting, lambda expressions, conditionals
Assignment Expressions
scm> (define kevin 61)
kevin
scm> kevin
61
scm> (define stan (+ kevin 1956))
stan
scm> stan
2017
>>> kevin = 61
>>> kevin
61
>>> stan = kevin + 1956
>>> stan
2017
Symbols and the Quote Expression
scm> (define life 42)
life
scm> life
42
scm> (quote life)
life
scm> ‘life ; shorthand for (quote life)
life
Lambda Expressions
scm> ((lambda (x) (* x x)) 4)
Operand
Operator
scm> (define square (lambda (x) (* x x)))
square
scm> (define (square x) (* x x))
square
…………………………………………………………………
scm> (square 4)
16
16
Conditions and Booleans
scm> (cond ((= 3 4) 4)
((= 3 3) 0)
(else 'burp))
0
(demo)
scm> (and false (/ 1 0) 5)
false
scm> (or true (/ 1 0) 5)
true
scm> (or 5 (/ 1 0) true)
5
Pairs and Lists
Scheme data structures
• The pair is the basic compound value in Scheme
• Lists in Scheme are created using pairs; they’re linked lists
Pairs and Lists
scm> (define x (cons 1 3))
x
scm> x
(1 . 3)
scm> (car x)
1
scm> (cdr x)
3
Pairs and Lists
scm> (define x (cons 1 (cons 2 (cons 3 nil))))
x
scm> x
(1 2 3)
scm> (car x)
1
scm> (cdr x)
(2 3)
scm> y
(1 2 3)
scm> (car y)
1
scm> (cdr y)
(2 3)
scm> z
(1 2 3)
scm> (car z)
1
scm> (cdr z)
(2 3)
scm> (define z ‘(1 2 3)) ; shortest-hand
z
scm> (define y (list 1 2 3)) ; shorthand
y
(demo)
Coding Tips
Example
(define (map fn lst)
(if (null? lst)
nil
(cons (fn (car lst)) (map fn (cdr lst)))))
(demo)
Example
(define (tree root branches)
(cons root branches))
(define (root tree) (car tree))
(define (branches tree) (cdr tree))
(define (leaf? tree) (null? (branches tree)))
(demo)
(define (square-tree t)
(tree (square (root t))
(if (leaf? t)
nil
(map square-tree (branches t)))))
Summary