Home > Articles > Programming > General Programming/Other Languages

  • Print
  • + Share This
  • 💬 Discuss
Like this article? We recommend

Pattern Matching

Pattern matching is where Prolog-like languages really come into their own, and Erlang is no exception. Most modern languages support some form of parametric polymorphism based on the types of arguments to a function. Erlang supports them based on the values.

Consider a function in a calculator that takes three arguments—an operation and two values. It then returns the result of applying the correct operation to the two values. In Erlang, it could be implemented something like this:

evaluate(add,A,B) ->
    A + B
;
evaluate(subtract,A,B) ->
    A - B
;
evaluate(multiply,A,B) ->
    A * B
;
evaluate(divide,A,B) ->
    A / B.

This example is slightly contrived, but it illustrates some of the power of the languages. Note the use of the semicolon (;) as a separator. In Prolog, a semicolon is a logical OR operation, and its meaning here is similar: Try the first version, and if that doesn’t work, try the next one. Note also the lack of an explicit return statement. Erlang functions (and blocks) return the value of the last line.

Pattern matching really starts to get fun when combined with the binary type. Consider an application that receives packets from a network and then processes them. The four bytes in a packet might be a network byte-order packet type identifier. In Erlang, you would just need a single processPacket function that could convert this into a data structure for internal processing. It would look something like this:

processPacket(<<1:32/big,RestOfPacket>>) ->
    % Process type one packets
    ...
;
processPacket(<<2:32/big,RestOfPacket>>) ->
    % Process type two packets
    ...
  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus