Structs

Table of Contents

1. Announcments

  • Lab Due Friday
  • Quiz Friday

2. Racket Tips

  • Commenting out chuncks of code -> #;
  • highlight entire code and press tab to format

3. Python vs Racket Grouping

In python: f vs. f() In Racket: f vs. (f) THERE IS A DIFFERENCE !

Parens has a meaning.. “()” can not be used for grouping

4. Exercise: Structs

background: write a function that takes in a family tree and returns the name of the maternal grandmother in the tree.

ft: family tree

4.1. 1) Data Defnitions

a FT is ether:

  • (person String FT FT), or
  • -1 <— anyhting that was not a person needed

(struct person (name mother father) #:transparent)

  • #:transparent allows us to see whats inside the struct when printing
           (define me
              (person "Brian"
                (person "Ilene" -1 -1)
                (person "Tom" -1 -1)))

Functions Available Once Struct Created:

> (person? me) #t

> (person-mother me) (person “Ilene” -1 -1)

> (person-name me) “Brian”

etc…

4.2. 2) Purpose statement and header

return maternal grandmother’s <— purpose statement

(define (gm-name ft)

  1. We are going to skip for now, but it’s important!
  2. write the function

(cond [(person? ft) (person-mother ft)] [else #f]))

<body>)

(define (m-name ft) (cond [(person? ft) (person-name ft)] [else #f]))

or

x and gmn are variables created and stored on the spot

           (match ft
                [(person n (person x (person gmn x x) x) x) gmn]
                [x #f])

4.3. 3) Tests

           (define me
              (person "Brian"
                (person "Ilene" (person "Sara" -1 -1) -1 -1)
                (person "Tom" -1 -1)))

           (check-equal? (gm-name me) "Sara")

Date: 2024-09-25 Wed 00:00

Author: Annthony R

Created: 2024-10-02 Wed 11:18