dwyl / learn-elixir

:droplet: Learn the Elixir programming language to build functional, fast, scalable and maintainable web applications!
1.61k stars 108 forks source link

Simple but *practical* explanation of pattern matching #57

Open iteles opened 7 years ago

iteles commented 7 years ago

Pattern matching is one of the core things to understand in Elixir, but I'm yet to find any really good explanations of pattern matching.

Most give you very basic implementations like https://elixirschool.com/en/lessons/basics/pattern-matching/#match-operator, which are ok but leave beginner with very little to build on.

What other things can be done with pattern matching? How is it useful in a live app? Can we add more advanced examples later in the tutorial?

YvesMuyaBenda commented 7 years ago

@iteles I have more to say about this topic--pattern matching is one of the many topics I am analyzing at the moment--but just to say something in the present: in investigating Erlang (in search of the best explanations), I found this rather neat example which uses pattern matching to define the has-someone-won function in tic-tace-toe:tic-tac-toe

The idea of "where you would use an algorithm, pattern match instead" is compelling, and perhaps a good angle to begin looking at the topic.

So the question in my mind: what is the basis for a "pattern-matching" refactoring?

Or perhaps another point of view to think of the question: if one took away the pattern-matching ability of the language, what kind of code would one have to write in specific contexts (no pun intentended)?

YvesMuyaBenda commented 7 years ago

For a concrete example of what I was talking about above, one use-case of pattern-matching is to reduce conditional logic. To give names to things, one might call it the "reduce conditional logic" pattern-matching refactoring pattern, where conditional logic, within the context of pattern-matching functional languages is a "code smell" which makes one pause and sniff and think and look at the code to see if the conditional is "really" required.