Lesson 22. Fixing the billion-dollar mistake

 

Hopefully, in the preceding lesson, you gained at least an initial appreciation of discriminated unions and how they allow you to quickly and easily model complex relationships. In this lesson, you’ll take a look at one specific discriminated union that’s built into F# and designed to solve a single problem: nothing! Or, more seriously, handling null values. You’ll learn about

  • Dealing with absence-of-value situations in .NET today
  • Working with optional data in F#
  • Using helper F# functions to deal with common optional scenarios

22.1. Working with missing values

Imagine you’re reading a JSON document from a car insurer that contains information on a driver, including a safety rating that’s used to calculate the driver’s insurance premiums. Better drivers get a positive score (and lower premium), whereas poor drivers get a negative score, as shown in figure 22.1. Unfortunately, the data is unreliable, so sometimes the JSON document won’t contain the safety score for a driver. In such a case, you’ll need to send a message to the data provider to request it at a later date again, and assign a temporary premium price of $300. The following listing shows such an example JSON document.

Figure 22.1. Annual insurance premiums on a sliding scale

22.2. Improving matters with the F# type system

22.3. Using the Option module

22.4. Collections and options

Summary