assistance-engine/docs/developer.avapframework.com/chapter9_49.md

34 lines
1.5 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## Sequence Patterns
In AVAP, sequence patterns are used to match elements within sequences like lists or tuples. The syntax for sequence patterns is:
```javascript
sequence_pattern ::= "[" [maybe_sequence_pattern] "]"
| "(" [open_sequence_pattern] ")"
```
Sequence patterns can match elements of sequences based on specific rules. Heres how they work:
* List Patterns: Use square brackets `[ ]` to match lists. You can include patterns for the elements within the list. `case [a, b, c]: print("Matched a list with three elements")`
* Tuple Patterns: Use parentheses `( )` to match tuples. Similarly, you can specify patterns for the tuple elements. `case (x, y): print("Matched a tuple with two elements")`
Sequence patterns allow for flexible and powerful matching of sequence types. They can match sequences of various lengths and structures by defining the pattern for each element.
Heres an example of using sequence patterns in a match statement:
```javascript
match value:
case [1, 2, 3]:
print("Matched a list with elements 1, 2, 3")
case (a, b, c) if a + b == c:
print("Matched a tuple where a + b equals c")
case _:
print("Matched something else")
```
In this example:
* `case [1, 2, 3]:` matches a list with exactly the elements 1, 2, and 3.
* `case (a, b, c) if a + b == c:` matches a tuple and includes a condition to check if `a + b` equals `c` .
* `case _:` matches any other value not covered by the previous cases.