| 16 | } |
| 17 | |
| 18 | void sample() |
| 19 | { |
| 20 | auto const words = std::vector<std::string>{"a", "b", "c"}; |
| 21 | auto const &slice = words; |
| 22 | Id<std::string> head; |
| 23 | Id<SubrangeT<std::vector<std::string> const>> tail; |
| 24 | match(slice)( |
| 25 | // clang-format off |
| 26 | pattern | ds() = [&] { std::cout << "slice is empty" << std::endl; }, |
| 27 | pattern | ds(head) = [&] { std::cout << "single element " << *head << std::endl; }, |
| 28 | pattern | ds(head, tail.at(ooo)) = [&] { std::cout << "head=" << *head << " tail=" << *tail << std::endl; } |
| 29 | // clang-format on |
| 30 | ); |
| 31 | |
| 32 | Id<SubrangeT<std::vector<std::string> const>> subrange; |
| 33 | match(slice)( |
| 34 | // clang-format off |
| 35 | // Ignore everything but the last element, which must be "!". |
| 36 | pattern | ds(ooo, "!") = [&] { std::cout << "!!!" << std::endl; }, |
| 37 | |
| 38 | // `subrange` is a slice of everything except the last element, which must be "z". |
| 39 | pattern | ds(subrange.at(ooo), "z") = [&] { std::cout << "starts with: " << *subrange << std::endl; }, |
| 40 | |
| 41 | // `subrange` is a slice of everything but the first element, which must be "a". |
| 42 | pattern | ds("a", subrange.at(ooo)) = [&] { std::cout << "ends with: " << *subrange << std::endl; }, |
| 43 | |
| 44 | pattern | ds(subrange.at(ooo)) = [&] { std::cout << *subrange << std::endl; } |
| 45 | // clang-format on |
| 46 | ); |
| 47 | |
| 48 | Id<std::string> penultimate; |
| 49 | match(slice)( |
| 50 | // clang-format off |
| 51 | pattern | ds(ooo, penultimate, _) = [&] { std::cout << "next to last is " << *penultimate << std::endl; } |
| 52 | // clang-format on |
| 53 | ); |
| 54 | |
| 55 | constexpr auto tuple = std::make_tuple(1, 2, 3, 4, 5); |
| 56 | // Rest patterns may also be used in tuple and tuple struct patterns. |
| 57 | Id<int32_t> y, z; |
| 58 | match(tuple)( |
| 59 | // clang-format off |
| 60 | pattern | ds(1, ooo, y, z) = [&] { std::cout << "y=" << *y << " z=" << *z << std::endl; }, |
| 61 | pattern | ds(ooo, 5 ) = [&] { std::cout << "tail must be 5" << std::endl; }, |
| 62 | pattern | ds(ooo ) = [&] { std::cout << "matches everything else" << std::endl; } |
| 63 | // clang-format on |
| 64 | ); |
| 65 | } |
| 66 | |
| 67 | int32_t main() |
| 68 | { |