Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does pattern matching work behind the scenes in F#?

Tags:

I am completely new to F# (and functional programming in general) but I see pattern matching used everywhere in sample code. I am wondering for example how pattern matching actually works? For example, I imagine it working the same as a for loop in other languages and checking for matches on each item in a collection. This is probably far from correct, how does it actually work behind the scenes?

like image 513
Kryptic Avatar asked May 25 '10 20:05

Kryptic


People also ask

How does pattern matching work?

Pattern Matching works by "reading" through text strings to match patterns that are defined using Pattern Matching Expressions, also known as Regular Expressions. Pattern Matching can be used in Identification as well as in Pre-Classification Processing, Page Processing, or Storage Processing.

What is pattern matching in functional programming?

Pattern matching allows you to match a value (or an object) against some patterns to select a branch of the code. From the C++ point of view, it may sound a bit similar to the switch statement. In functional languages, pattern matching can be used for matching on standard primitive values such as integers.

How pattern matching is used in scripting language?

The implementation of pattern matching into JavaScript greatly aids in the processing of data for the Internet. JavaScript uses the RegExp (short for Regular Expression) object to handle pattern matching. This object holds the pattern definition, as well as provides methods for performing matching.


1 Answers

How does pattern matching actually work? The same as a for loop?

It is about as far from a for loop as you could imagine: instead of looping, a pattern match is compiled to an efficient automaton. There are two styles of automaton, which I call the "decision tree" and the "French style." Each style offers different advantages: the decision tree inspects the minimum number of values needed to make a decision, but a naive implementation may require exponential code space in the worst case. The French style offers a different time-space tradeoff, with good but not optimal guarantees for both.

But the absolutely definitive work on this problem is Luc Maranget's excellent paper "Compiling Pattern Matching to Good Decisions Trees from the 2008 ML Workshop. Luc's paper basically shows how to get the best of both worlds. If you want a treatment that may be slightly more accessible to the amateur, I humbly recommend my own offering When Do Match-Compilation Heuristics Matter?

Writing a pattern-match compiler is easy and fun!

like image 181
Norman Ramsey Avatar answered Nov 15 '22 10:11

Norman Ramsey