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?
Share
It depends on what kind of pattern matching do you mean – it is quite powerful construct and can be used in all sorts of ways. However, I’ll try to explain how pattern matching works on lists. You can write for example these patterns:
The F# list is actually a discriminated union containing two cases –
[]representing an empty list orx::xsrepresenting a list with first elementxfollowed by some other elements. In C#, this might be represented like this:The patterns above would be compiled to the following (I’m using pseudo-code to make this simpler):
As you can see, there is no looping involved. When processing lists in F#, you would use recursion to implement looping, but pattern matching is used on individual elements (
ConsList) that together compose the entire list.Pattern matching on lists is a specific case of discriminated union which is discussed by sepp2k. There are other constructs that may appear in pattern matching, but essentially all of them are compiled using some (complicated)
ifstatement.