pegged.examples.pattern

This module is an attempt at introducing pattern-matching in D.

Pattern matching is a type- or value-matching present in functional languages like ML or Haskell.

The goal here is to obtain code like:

1 Pattern!"[ a, b, ... ]" p1; // match any range with at least two elements
2                             // the rest being discarded.
3 
4 auto m1 = p1([0,1,2,3,4]); // match and associate 'a' and 'b' with O and 1.
5 assert(m1.a == 0 && m1.b == 1);
6 auto m2 = p1("abc");
7 assert(m2.a = 'a' && m2.b == 'b');
8 auto m3 = p1(tuple("abc",0)); // not a range, the pattern fails
9 assert(m3 == matchFailure; // predefined constant
10 
11 Pattern!"Tuple!(.,.) t" p2; // match any std.typecons.Tuple with two elements, of any type
12 auto m4 = p2(tuple("abc",0));
13 assert(m4.t = tuple("abc",0); // only the global pattern is named, and hence captured
14 assert(p2(tuple("abc")) == matchFailure); // only one member -> failure
15 assert(p2(tuple("abc",0,1)) == matchFailure); // three members -> failure (the pattern has no trailing ...
16 
17 Pattern!" . { int, double, double }" p3; // match any aggregate (struct, class)
18                                          // with three members being int,double and double, in that order.

Don't salivate, it's not implemented yet.

Members

Structs

TypeDiscardMatch
struct TypeDiscardMatch(alias Pattern)

Discards the matched types, but propagate the indices.

Meta