Im wondering how pattern matching is usually implemented. for example in Erlang do you think its implemented at the byte-code level(there's a bytecode for it so that its done efficiently) or is it generated as a series of instructions(series of bytecodes) by the compiler? it is such a useful thing that I just have to put it into a toy language Im building thank you very much
(links are more then welcome)
If you want to build your own pattern matcher there is a paper by Scott and Ramsey and a paper by Luc Maranget which both describe how to compile patterns to efficient decision trees (aka nested switch statements).
A very good description of compiling pattern matching is given in "The implementation of functional programming languages" by Simon Peyton Jones. It is a bit old but a very good book. It also contains, amongst other things, a description of compiling list comprehensions.
The Erlang compiler uses both of these algorithms from the book.
You can see what happen if compile some code
When you want see how looks like core
or
result is
If you want see asm code of beam you can do
or
and result
As you can see
{test,is_tuple,...
,{test,test_arity,...
,{get_tuple_element,...
and{test,is_eq_exact,...
are instruction how this match is performed in beam and it's transformed directly to byte-code of beam.Erlang compiler is implemented in Erlang itself and you can look at each phase of compilation in source code of compile module and details in depend modules.
The best thing I can suggest is to compile up some test functions and have a look at the generated code.
generates test.S which is fairly readable.
To answer the question, pattern matches are built up in an efficient way from more primitive operations. Here's part of the code from a function clause matching {X, [H|T]}.