Title: Structures in Scheme
1Structures in Scheme
CS 480/680 Comparative Languages
2Scheme Structures
- Structures in scheme are already nearly objects
- When you create a structure, you define the data
members, and you automatically get accessor and
modifier procedures
3Defining a Structure
- (define-struct tree (height girth age leaf-shape
leaf-color)) - Object is of type tree with fields height,
girth, etc. - Accessors tree-height, tree-girth, tree-age, etc.
are automatically created - Modifiers set-tree-height!, set-tree-girth!,
set-tree-age!, etc. are automatically created - Constructor make-tree is automatically defined
4Using the Tree
(define-struct tree (height girth age
leaf-shape leaf-color)) (define coconut
(make-tree 30 40 7 frond green) (tree-height
coconut) 30 (tree-leaf-shape coconut)
frond (set-tree-height! coconut
40) (set-tree-girth! coconut 10) (tree? coconut)
t
Initializers for data members must be supplied to
the constructor as arguments
5Using the Tree
(define-struct tree (height girth age leaf-shape
leaf- color)) (define coconut (make-tree 30
40 7 frond green) (tree-height coconut)
30 (tree-leaf-shape coconut) frond (set-tree-h
eight! coconut 40) (set-tree-girth! coconut
10) (tree? coconut) t
Define-struct is a macro which quotes these
arguments
6Using the Tree
(define-struct tree (height girth age leaf-shape
leaf- color)) (define coconut (make-tree 30
40 7 frond green) (tree-height coconut)
30 (tree-leaf-shape coconut) frond (set-tree-h
eight! coconut 40) (set-tree-girth! coconut
10) (tree? coconut) t
Note how a symbol without a value can be used as
an enumerated type
7Hashes in Scheme
(define h (make-hash-table)) (hash-table-put! h
name mike) (hash-table-put! h score
95) (hash-table-get h name) mike (hash-table-co
unt h) 2 (hash-table-get h 'bob (lambda () f))
Run this procedure if the key is not found.
8Operating on hashes
- (hash-table-for-each h proc) runs proc on each
key, value pair in h - No return value of proc, side-effects only
- (hash-table-for-each h (lambda (key value) (begin
(display key) (display value)))) - (hash-table-map h proc) same as for-each, but
accumulates return values and returns a list
9Exercises
- Write a scheme program that creates a list of
three structures and then accesses the members of
each one - Write a program that reads in a list of student
data (first, last, ssn, grade1, grade2, grade3)
and makes a list of student structures