Pattern matching is a little strange at first, so we're going to ease into it slowly...
There are two aspects to pattern matching: patterns, which you write, and matching, which is what Pyke does with your patterns.
In a nutshell, patterns are made up of two fundamental building blocks:
- Literal patterns.
- Theses are just data values that only match themselves.
- Pattern variables.
- These will match anything. (Including other pattern variables, as we'll see later)!
And one compound pattern:
- Tuple patterns.
- These match -- you guessed it! -- tuples!
We'll examine all of the above looking at how Pyke matches a pattern to data. Then we'll expand this to cover matching two patterns together.
And finally, a pathological question to see if you've been paying attention.
Sound like fun? Good! Let's get started!
OK, so why do we need patterns? The simple answer is that we need patterns to generalize statements. One example is to turn statements into questions.
- When you want a direct statement, such as to state a fact, you just use data for its arguments.
- But when you want a generalized statement, such as to ask a question, you use patterns for its arguments.