Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

What are some applications of pattern matching?


You know how a lot of jQuery functions take either a string, or a function, or an array of strings, etc? Instead of making those decisions in your code in a series of IF statements, you could use this library and just maintain a "map" of the different argument forms and have this library dispatch the right option.

In Erlang, this is used all the time to make functions that behave differently depending on how they're called - for instance, massaging a binary string into a regular string if the function only expects a regular string.

This is a small tool in a programmer's toolkit, but could be a handy one.


Pattern matching is common in functional languages like Haskell or Scala. It's like a form of overloading on steroids, letting you inspect the values and structure of the arguments passed to your function (with a very terse syntax), and do different things based on that criteria. It can also take care of a lot of boilerplate like splitting an array into different parts or extracting values from a configuration object.


Think of it as declarative nested if statements. Concise like a switch but generalized to typed values.




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

Search: