Pattern matching in C++ and D

Francesco Mecca me at francescomecca.eu
Tue Jan 7 14:00:01 UTC 2020


I found a paper regarding a proposal for pattern matching in C++ 
on HN a few days ago:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1371r1.pdf

Given the time I spent with OCaml and the OCaml compiler recently 
I find that pattern matching is an essential feature for a modern 
language and that there are cases in which the pattern matching 
compiler outputs better code than nested handwritten if-else-if's.

In D we have the Sumtype library that is an excellent library for 
sumtypes and coincidentally provides pattern matching based on 
the type of the value being matched.

As outlined from the paper there are many other kinds of pattern 
that could be very useful in current D code. I won't make 
examples here because the paper is full of examples that are 
pretty easy to mentally translate from C++ to D.

In the "Design Decision" chapter of the paper the authors discuss 
about not restricting side effects. In OCaml there are the same 
problems with guards that could have side effects. Example:

```
let function_with_side_effects x = ...
let match x = match x with
     | p1 -> e1
     | p2 when function_with_side_effects x -> e2
     | _ -> e3
```

If x is modified by functions with side effects the pattern 
matching could be not exhaustive and in the worst case the result 
undefined. The same applies when a guard uses boolean comparison 
that has been overridden by the developer.

In D we can do better than that by forcing guard expressions to 
be pure.
I also believe that ranges provides a better interface for a more 
expressive pattern matching but I have to think more about that 
(the paper shortly discuss that in section 10.2).

The main shortcoming with D is that we don't have a builtin tuple 
type and destructoring assignments.
Timon Gehr was working on that 
(https://github.com/tgehr/DIPs/blob/tuple-syntax/DIPs/DIP1xxx-tg.md) but the last commit is 2 years old.





More information about the Digitalmars-d mailing list