Using the Pin Operator
The Pin Operator
Welcome back. In the previous lesson, you matched data shapes using case and refined matches with guards. Today, you’ll add the pin operator (^) to match against an existing variable’s value instead of rebinding it. You will also:
- See pin used in function heads, map keys, lists, and binaries.
- Contrast pin vs guards for readability and intent.
- Understand how pin prevents accidental rebinding.
- Combine pin with recursion for targeted transformations.
- Learn when pin helps and when it hurts readability.
Rebinding Prevention: Why ^ Matters
Variables in patterns normally rebind. Pin stops that.
Explanation:
- Without pin,
expectedis rebound inside the pattern and the first clause matches any value. - With pin, the value must equal the previously bound
expected, otherwise it falls through.
Match a Specific Value with ^
Explanation:
- The caret (
^) “pins”expected, so the pattern comparesvalueto the current value ofexpectedinstead of rebindingexpected. - Without the pin,
expectedwould be rebound inside the pattern, which is not what we want here.
Replace Items in a List with a Pin Pattern
Using a pin directly in the pattern is often clearer than a guard for equality checks:
Explanation:
fn ^old_value -> new_valuematches the element only when it equalsold_value, no guard needed.- This communicates “match this exact value” at the pattern level.
For contrast, here’s the guard version you saw earlier:
