Modeling Optional Values, Errors, and Collections

While we are discussing domain modeling, let’s talk about some common situations and how to represent them with the F# type system, namely:

  • Optional or missing values
  • Errors
  • Functions that return no value
  • Collections

Modeling Optional Values

The types that we have used so far—records and choice types—are not allowed to be null in F#. That means that every time we reference a type in a domain model, it’s a required value.

So how can we model missing or optional data?

The answer is to think about what missing data means: it’s either present or absent. There’s something there, or nothing there. We can model this with a choice type called Option, defined like this:

 type​ Option<​'​a> =
  | Some ​of ...

Get Domain Modeling Made Functional now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.