Recitation 7 — Structured and conditional data
Skills: 4
Reading: 6.1, 6.2
Structured Data
Many pieces of real-world information consist of several parts that should be kept together. Structured data bundles multiple fields into a single value.
Defining a Structured Data Type
Define a new data type called Student
to represent a student:
data Student:
| student(name :: String, id :: Number, gpa :: Number)
end
Creating Examples
Create instances of Student
using the constructor student
:
alice = student("Alice Smith", 12345, 3.7)
bob = student("Bob Martinez", 23456, 3.2)
carol = student("Carol Johnson", 34567, 3.9)
What do you expect to happen if you try to create a student with a string for the ID number?
Extracting Fields
Design a function student-info
that returns a formatted string for a student:
What is the result of `student-info(alice)`?
### Writing Functions with Structured Data
Design a function `honors-student` that returns true if a student has a GPA of 3.5 or higher:
## Conditional Data
Sometimes data can come in multiple forms and we need a way to represent alternatives within one type. Conditional data can be one of several variants.
### Defining a Conditional Data Type
Define a new type called `OrderType` with three variants:
```pyret
data OrderType:
| pickup
| delivery(address :: String, tip :: Number)
| curbside(car-color :: String, license-plate :: String)
end
How many different ways can someone receive their order according to our OrderType?
Creating Examples
Create instances of OrderType
:
order-1 = pickup
order-2 = delivery("360 Huntington Ave, Boston MA", 5.00)
order-3 = curbside("red", "ABC123")
Taking Apart Variants with cases
Design a function order-instructions
that returns instructions for fulfilling an order:
fun order-instructions(o :: OrderType) -> String:
cases (OrderType) o:
| pickup => # YOUR CODE HERE
| delivery(addr, tip-amount) => # YOUR CODE HERE
| curbside(color, plate) => # YOUR CODE HERE
end
where:
order-instructions(pickup) is "Order ready for pickup at counter"
order-instructions(order-3) is "Look for red car with plate ABC123 in parking lot"
end
Processing Fields in Variants
Design a function total-cost
that calculates the total cost including any service fees:
What information do we use and ignore in each case?
Wrap-Up
When would you use structured data instead of separate variables? Why is pattern matching with cases
better than using if-statements for conditional data?