I know the gist of pattern matching, where you manipulate data structures upon runtime. I know that pattern matching takes 4 arguments: the pattern to match against, the expression to match, a success continuation, and a failure continuation. However, after that, looking at Racket Documentation I am lost. I don't understand specifically (with concrete, line-by-line, explained examples) how to implement this into a code, and what to do with it. Could someone please explain to me a dumbed-down version of pattern matching, perhaps with a basic code to help me out?
2 Answers
With pattern matching, we want to tear apart datastructures, so we pass in a piece of data to destruct
(match foo
...)
Next we need to specify a list of constructors to try foo
against. If foo
was constructed by one of those constructors, we bind foo
s fields to the variables specified and run the associated block.
(match foo
[(list a b) (+ a b)]
[_ (displayln "Hey that's not a list!")])
That's it! If foo
is a list of two elements, we run + a b
if not, we run the other continuation and print that foo
isn't a list.
It sounds like maybe you have a school assignment to implement a pattern-matching engine?
If so, you may find it interesting to watch this lecture, 4A: Pattern Matching and Rule-based Substitution.
The lecture is by some guy who seems to know what he's talking about. He talks about the concepts, how to break the problem into smaller pieces, and even shows many code samples.