(require racket)
(require racket/base)
We want to define a data structure for a person, comprising the person's name, age, and college. In racket, we could use a list, such as the following.
(define person1 '(joe 25 cornell))
We can access the slots using the standard selectors, such as car, cdr, first, etc.
(car person1)
'joe
(second person1)
25
(caddr person1)
'cornell
The problem is that someone looking at your code -- including you -- does not know that (car person1) is the name. Also, we won't accidentally
We solve this problem and make our code
(cadddr person1)
cadddr: contract violation expected: (cons/c any/c (cons/c any/c (cons/c any/c pair?))) given: '(joe 25 cornell)
The solution in racket is to use struct, which facilitates named access to data structures. Here is struct in action.
(struct person (name age college) #:transparent)
The name of the struct is also the constructor.
(define p1 (person 'john 23 'yale))
(define p2 (person 'mary 20 'yale))
p1
(person 'john 23 'yale)
p2
(person 'mary 20 'yale)
The selectors for the struct are the name with a hyphen prefixed to the slot names.
(person-name p1)
'john
(person-age p1)
23
(person-college p2)
'yale
struct comparison uses equal? not =.
(equal? p1 p2)
#f
(equal? p1 p1)
#t
(equal? p1 (person 'john 23 'yale))
#t
(= p1 (person 'john 23 'yale))
=: contract violation expected: number? given: (person 'john 23 'yale) argument position: 1st other arguments...: (person 'john 23 'yale)
The predicate for a struct is the name with a ? suffix.
(person? p1)
#t
(person? 'p1)
#f
An instruction is a 5-tuple
(struct ins (c-state c-symbol n-state n-symbol dir) #:transparent)
(struct ins (c-state c-symbol n-state n-symbol dir) #:transparent)
A configuration is a current state, a head position, and a tape
(struct conf (state ltape symbol rtape) #:transparent)
(struct conf (state ltape symbol rtape) #:transparent)
A tape is just a list of symbols
(define tape1 '(1 1 0 1 0))
(define tape2 '(b 1 1 b 0 1 1 b b))
(define config1 (conf 'q1 '(0 1) 0 '(1 1)))
(conf-state config1)
'q1
(conf-symbol config1)
0
(conf-ltape config1)
'(0 1)
(conf-rtape config1)
'(1 1)
(define tm1
(list
(ins 'q1 0 'q1 1 'R)
(ins 'q1 1 'q1 0 'R)
(ins 'q1 'b 'q2 'b 'L)
(ins 'q2 0 'q2 0 'L)
(ins 'q2 1 'q2 1 'L)
(ins 'q2 'b 'q3 'b 'R)))