21 Pattern Matching

How do we break data types apart? We can use pattern matching.

Here, we're matching the pattern not true. It works kind of similar to a switch statement.

Here, we've matched against 42 with a pattern variable, a in this case.

By the way, each match item is called a branch.

In this example, _ is a wildcard. It matches anything. We can also use pattern matching with other types.

Here, OCaml matched the empty list [] with the empty list []. On the other hand, if we matched it with a non empty list, it would return "not empty".

What if we want to do something more powerful?

What if we tried to return t?

Uh oh! That happens because t is a string list (["swift"]), while "folklore" is a string. We can fix this by making folklore a string list:

We can also do this with tuples! Say we wanted to define a function to get the first item out of a 3-tuple:

What if we wanted to write a function that returns the name and the school year of a student, from our previous examples?