# CS790 – Introduction to Bioinformatics

Βιοτεχνολογία

4 Οκτ 2013 (πριν από 4 χρόνια και 7 μήνες)

99 εμφανίσεις

Structures in Scheme

CS 480/680

Comparative Languages

Structures

2

Scheme 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

Structures

3

Defining 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

Structures

4

Using 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

Structures

5

Using 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

Define
-
struct is a
macro

which
quotes

these
arguments

Structures

6

Using 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

Note how a
symbol without a
value can be used
as an enumerated
type

Structures

7

Hashes 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
-
count h) » 2

(hash
-
table
-
get h 'bob (lambda () #f))

Run this procedure if

Structures

8

Operating 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

Structures

9

Exercises

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