00:01 The simplest use case for union types is when you have a list of options. For example, this is how you define a rating type where we have three options -- excellent, good, and poor. To create a rating, you just use one of these options.
00:19 Let's say that our data, instead of being of type string, is of type rating, and its value is "excellent." If I try to run this program as-is, you can see that it complains, because the text function expects an argument of type string, whereas data is now of type rating.
00:46 We can fix that by using the two-string function that's an in-built function which will take an argument of any type and convert it to a string. We also need parenthesis. Now it works, and our data of type rating is rendered as "excellent."
01:24 This is simple, and it's similar to enumerations as we have in other languages, but union types in Elm are more powerful because these options -- excellent, good, and poor -- they're not just values, they're functions. They're actually called constructors. You could parameterize these functions.
01:40 You could say that there's another constructor, other, that takes a string, and you could use this other with a string to create a rating. For example, you could say that data is an other with a string, "appalling." In this case, we're giving the user three predefined ratings and a way to build a rating with an arbitrary string.
02:01 This compiles and works as expected. Let's say that in the rendering you didn't want this other to appear. You want to create a custom rendering that is not exactly the same as the built-in two-string function.
02:17 You can do this with pattern matching. For example, you could create a function called render which takes a rating and returns a string. Let's implement this. We take a rating, and then we use the case keyword to pattern match on the rating, and we say that if this is an other with an S, then we return S, and this other S basically runs the constructor backwards and extracts the string that the other was built with and calls it S.
02:56 Now you can cater for the other cases. If the rating is excellent, then return the string excellent and so on, but to make this a bit shorter, let's add a catch-all case and return two-string rating. This render function only does something special if the given rating is an other and otherwise just uses the two-string function.
03:22 Now let's use render instead of two-string. Now, if we run this again, you can see that the other is gone, and it just shows "appalling."