This article was first published on RChain Cooperative - Medium
Rholang Lesson 11: Pattern Matching
Patterns occur all over in daily life. If you saw a new model of car that you had never seem before you would still know it is a car because it matches a mental pattern you have for cars that probably involves four wheels, two or four doors, and a windshield to see out of.
Similarly, we can match sentence patterns. The sentences “I like cheese” and “I like pandas” both match the pattern “I like ____”. But “I have a dog” does not match that pattern. Rholang allows programmers to use pattern matching to control program execution. That is, different code can run depending whether a process matches a certain pattern.
The match construct
The most obvious place that rholang uses pattern matching is in its match construct which works as shown here.
In this code any massage x that is received on the patternMatcher channel represents a quoted process. We compare that process (unquoted) to several patterns below and report back what pattern matches. The underscore is just a fill-in-the-blank and matches any pattern at all. It is called a "wildcard", and you'll often see it as the final pattern in a matchconstruct to ensure that there is a default case if nothing else matches.
Pattern matching can also be used when receiving messages with for or contract. In order for a message to be received, the message that was sent, must match the pattern that is to be received. We'll see an example of this usage shortly.
Two cases we’ve seen
We’ve already used the underscore occasionally. For example I often write for (_ <- ack) which means, receive a message matching any pattern on the ack channel. It is standard practice to use the ...
To keep reading, please go to the original article at:
RChain Cooperative - Medium