Hacker News new | past | comments | ask | show | jobs | submit login

Would someone please explain what he means by "pattern matching" in this context?



The discussion in Learn you some Erlang is probably good enough: http://learnyousomeerlang.com/syntax-in-functions

Python already has something accessible and similar in it's tuple unpacking. For example it allows:

a,b,c = (1,2,3)

Here the variables are being filled by values from the tuple based purely on their position within it.

Pattern matching takes this a few steps further by allowing you to mix known values into things and combine dispatch from those values with variable assignment.

For example, imagine that Python had the following Python expression give a true/false value based on if the elements match:

"test", a, b = ("test", 1, 2) # would evaluate to True and bind a=1, b=2

"test", a, b = ("nope", 1, 2) # would evaluate to False and would not bind a or b

This can clean up a surprising amount of code, especially if you structure a case statement around it.

The double-whammy is when you allow a function to be defined multiple times so long as each definition has a different pattern match in the variable declaration. The Erlang article I linked to covers this topic pretty well.


It's a feature in Erlang - this is a reasonably brief explanation:

http://learnyousomeerlang.com/syntax-in-functions

You can think of it as a smart way of doing a switch statement that takes the number and type of arguments in to account - though that's a huge simplification.


Pattern matching is the process of defining multiple functions with the same number of arguments, where the arguments decide which function to execute.

E.g.: foo(0) -> 1; foo(n) -> foo(n) * foo(n-1).

calls to foo(0) would execute the first function, while all other calls would execute the 2nd. Note that it is often necessary to define the functions in order of most specific first.

A similar concept in Erlang is guards, where an expression can be evaluated instead of simple pattern matching.

foo(n) where n == 0 -> 1; foo(n) -> foo(n) * foo(n-1).

Might have screwed up on the Erlang notation in that example though.


This is why you don't write code before your morning shot of caffeine (unending recursive function calls). Meh.


Interesting that the two replies so far cited the exact same URL to answer your question.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: