Skip to content

San Francisco: MPark.Patterns — Pattern Matching in C++

Photo of Arthur O'Dwyer
Hosted By
Arthur O. and Michael P.
San Francisco: MPark.Patterns — Pattern Matching in C++

Details

This time for sure! Michael Park couldn't present on 2017/09/06, but now he's recuperated and ready to talk about pattern matching. This will be the final entry in our "CppCon session rehearsal" series. Notice that we're back at Mesosphere for this one.

Pattern matching brings a declarative approach to destructuring and inspecting complex data types. It’s a very powerful abstraction provided by many programming languages such as Haskell and OCaml, and more recently, Rust, Scala, and Swift.

We’ll see a glimpse of pattern matching in C++17 and their current limitations through features such as structured bindings, `apply`, and `visit`. We’ll then jump into MPark.Patterns, an experimental pattern matching library for C++. The following is an example of FizzBuzz (https://imranontech.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/) written with the library:

void fizzbuzz() {
for (int i = 1; i <= 100; ++i) {
using namespace mpark::patterns;
match(i % 3, i % 5)(
pattern(0, 0) = [] { std::cout << "fizzbuzz\n"; },
pattern(0, ) = [] { std::cout << "fizz\n"; },
pattern(
, 0) = [] { std::cout << "buzz\n"; },
pattern(_, _) = [i] { std::cout << i << '\n'; }
);
}
}

We’ll see many more examples like this that lead to simpler, declarative code that focuses on the desired shape/state of the data, rather than a sequence of imperative code that tries to inspect the data in piecemeal.

The goal of the library, and the talk, is to gain experience and exposure to pattern matching in order to potentially help guide the design of a language-based pattern matching mechanism.

Michael Park is a committer for the Apache Mesos project and works as a Distributed Systems Engineer at Mesosphere. Within the realm of computer science, he's very much intrigued by language design, compiler construction, and distributed systems. Michael is also an active member of the ISO C++ Standards Committee.

Level of Expertise: Intermediate

Photo of Cpp Bay Area: C++ Programming In and Around Silicon Valley group
Cpp Bay Area: C++ Programming In and Around Silicon Valley
See more events