30 lines
1.3 KiB
Markdown
30 lines
1.3 KiB
Markdown
## AS Patterns
|
|
|
|
An AS pattern in AVAP is used to bind an OR pattern to a name. This allows you to match a value with an OR pattern and simultaneously capture it under a specified name for further use. The syntax for an AS pattern is:
|
|
|
|
```javascript
|
|
as_pattern ::= or_pattern "as" capture_pattern
|
|
```
|
|
|
|
When an AS pattern is used, if the OR pattern succeeds, the subject is bound to the name specified by the capture pattern, and the AS pattern itself succeeds.
|
|
|
|
Here's an example of how to use AS patterns:
|
|
|
|
```javascript
|
|
match value:
|
|
case 1 | 2 | 3 as x:
|
|
print(f"Matched a number: x")
|
|
case "hello" | "world" as greeting:
|
|
print(f"Matched a greeting: greeting")
|
|
case _:
|
|
print("No match")
|
|
```
|
|
|
|
In this example:
|
|
|
|
* The first case matches if `value` is 1, 2, or 3. The matched value is bound to the name `x` , which is then used in the print statement.
|
|
* The second case matches if `value` is "hello" or "world". The matched value is bound to the name `greeting` , which is then used in the print statement.
|
|
* The last case is a catch-all pattern that executes if none of the previous patterns match.
|
|
|
|
AS patterns are useful for capturing matched values under a name while using OR patterns, allowing for more flexible and readable pattern matching in your code.
|