Understanding Structured Data in Pyret
In Pyret, structured data allows us to group related pieces of information into a single
entity, making our programs more organized and easier to manage. Let's explore how to
define and work with structured data in Pyret through a practical example.
**Defining Structured Data**
Suppose we want to represent a song in a music library, capturing details like the title,
artist, duration, and genre. We can define a `Song` data type with these fields:
```pyret
data Song:
| song(title :: String, artist :: String, duration :: Number, genre :: String)
end
```
This definition introduces a `Song` data type with a constructor `song` that takes four
parameters: `title`, `artist`, `duration`, and `genre`.
**Creating Instances of Structured Data**
With the `Song` data type defined, we can create instances (i.e., specific songs) as follows:
```pyret
my_favorite_song = song("Imagine", "John Lennon", 183, "Rock")
another_song = song("Bohemian Rhapsody", "Queen", 354, "Rock")
```
**Accessing Fields in Structured Data**
To retrieve information from a structured data instance, we can access its fields directly:
```pyret
my_favorite_song_title = my_favorite_song.title
another_song_duration = another_song.duration
```
**Defining Functions to Process Structured Data**
We can define functions that operate on our structured data. For example, to check if a song
is longer than a certain duration:
```pyret
fun is_longer_than(song_instance :: Song, length :: Number) -> Boolean:
song_instance.duration > length
end
```
**Working with Lists of Structured Data**
Often, we'll work with collections of structured data. For instance, a playlist can be
represented as a list of `Song` instances:
```pyret
playlist = [list: my_favorite_song, another_song, song("Thriller", "Michael Jackson", 358,
"Pop")]
```
To filter songs of a specific genre from the playlist:
```pyret
fun filter_by_genre(songs :: List<Song>, desired_genre :: String) -> List<Song>:
[Link](lam(s): [Link] == desired_genre end)
end
```
**Example Usage**
Let's use the `filter_by_genre` function to get all Rock songs from our playlist:
```pyret
rock_songs = filter_by_genre(playlist, "Rock")
```
This would result in a list containing "Imagine" by John Lennon and "Bohemian Rhapsody"
by Queen.
By utilizing structured data in Pyret, we can effectively model complex information, leading
to more readable and maintainable code.