Check out a free preview of the full Introduction to Elm, v2 course:
The "Pattern Matching & Review" Lesson is part of the full, Introduction to Elm, v2 course featured in this preview video. Here's what you'd learn in this lesson:

Pattern matching is utilized in a case-expression to handle the possibility of an HTTP request succeeding or failing. Richard reviews what was learned in the last few sections before going on to the exercise.

Get Unlimited Access Now

Transcript from the "Pattern Matching & Review" Lesson

>> Richard Feldman: One last thing to note is that when we have this CompletedLoadFeed variant and it's holding onto results. Since result is also custom type, we can actually write what is known as pattern match that will handle both of these at the same time. What I mean by that is instead of saying CompletedLoadFeed and then saying results right over here and then doing a case on that result, we can actually specify both of these at the same time.

[00:00:27] And this is typically how it's done. So this is a if I got a CompletedLoadFeed message, and the result inside was an Ok, here's what I wanna do. And then, also, if I got a CompletedLoadFeed message, or I got an error for this result, then I wanna do this other thing.

[00:00:45] So this is a short hand for writing out CompletedLoadFeed result, and then case result of, and doing a nested case expression. This let's us, instead of nesting it, just enumerate the two different possible paths that could go with that nested case expression. And just say, okay, I wanna handle this one, and I wanna handle this one, and doing those both at the top level.

[00:01:04] Typically, this is how people do it with HTTP requests. So they are all handled right in the same case expression. That's known as pattern matching. That brings us to the conclusion of part 8. So first we learned about Tuples which are essentially short hands for records where fields are access by position rather than by name.

[00:01:22] We saw how did you randomness in Elm, with Random.generate and how that works through our command. Because Elm has this function guarantees of all functions that are given the same arguments must return to the same value. We saw that commands are a description of some effect to be run by the Elm run time.

[00:01:40] They don't actually run anything when you instantiate them, you can make a thousand of them and that will do absolutely nothing. It's only when update returns one of them that the run time will take that value and actually execute it. And finally, we learned how to do HTTP using tuples and commands by converting some description of what we want the HTTP request to be into a command by using Http.send and passing it what to do in the case of success and what to do in the case of failure.

[00:02:07] Which generally means, wrapping up that result that specifies either it succeeded or it failed inside a message variant.