Lesson 21. Modeling relationships in F#
Although you’ve looked at different ways of storing data in F# (tuples, records, and so forth), one thing you haven’t looked at much is how to model relationships of data together—for example, different types of motor vehicles such as cars, motorbikes, and vans. In this lesson, you’ll look at a way of doing this in F#, using a flexible and powerful modeling tool called discriminated unions. You’ll do the following:
- Briefly review inheritance in the OO world
- Learn what discriminated unions are, and how to use them
- Compare and contrast inheritance and discriminated unions
You’re probably familiar with modeling relationships in C# already, through one of two mechanisms: composition and inheritance. The former establishes a has-a relationship, whereas the latter typically models the is-a relationship; for example:
- A computer has a set of disk drives.
- A printer is a device.
We covered composition in lesson 10, where you created two record types with one referencing the other, but let’s quickly recap it with another example.
Listing 21.1. Composition with records in F#
type Disk = { SizeGb : int } type Computer = { Manufacturer : string Disks: Disk list } #1 let myPc = { Manufacturer = "Computers Inc." Disks = #2 [ { SizeGb = 100 } { SizeGb = 250 } { SizeGb = 500 } ] }