Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fay-jai/13f13ad6739ae619be2d9ff11f50cda4 to your computer and use it in GitHub Desktop.
Save fay-jai/13f13ad6739ae619be2d9ff11f50cda4 to your computer and use it in GitHub Desktop.
# Pattern Matching and Multiple Function Clauses in Elixir
greet = fn # The `fn` keyword starts the function definition
("Willson") -> "Wassup Willson!!" # A function clause consists of a parameter list and a body. In this case, we have defined 2 function clauses
(name) -> "How are you doing, #{name}?" # Notice that both function clauses have the same number of arguments (1, in this case).
end # The `end` keyword ends the function definition
greet.("Tiffany") # This returns "How are you doing, Tiffany?"
greet.("Willson") # This returns "Wassup Willson!!"
# Why does calling the `greet` function result in different outcomes above?
# This is the magic of pattern matching with Elixir functions.
# This is what happens when we call `greet.("Tiffany")`:
# 1) Elixir checks the first function clause to see if it pattern matches the argument "Tiffany" with it. In other words, its checking whether "Willson" == "Tiffany"
# 2) This pattern match isn't successful, and so Elixir continues checking the next function clause and sees if it pattern matches successfully.
# 3) In this case, the pattern match looks like this: name = "Tiffany". This pattern match will be successful because we can bind the value "Tiffany" to the variable `name` to create a match.
# 4) Since it passes the pattern match, this particular function clause and its body will be invoked with the argument.
# Using the same logic as above, you can now understand what happens when `greet.("Willson")` is called. It checks the first clause and immediately matches.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment