I'm new to Elixir. I have this code:
defmodule DefaultParams do
def func(p1, p2 \\ 2, p3 \\ 3, p4) do
IO.inspect [p1, p2, p3, p4]
end
end
With this code, I do:
DefaultParams.func("a", "b") #=> ("a", 2, 3, "b")
I understand why it works that way: because of pattern matching. Elixir tries to match the supplied parameters to the ones defined in the function definition.
However, I don't understand this:
DefaultParams.func("a", "b", "c") #=> ("a", "b", 3, "c")
Why is the output not ("a", 2, "b", "c")
? That also fits the pattern defined in the parameters. I looked for an in-depth explanation in the docs but couldn't find anything.
After thinking about it for a while, I developed the suspicion that it works like this:
Can someone confirm/explain?
edit: fixed typos
Pattern matching is the process of checking whether a specific sequence of characters/tokens/data exists among the given data. Regular programming languages make use of regular expressions (regex) for pattern matching.
Pattern recognition is the use of machine learning algorithms to identify patterns. It classifies data based on statistical information or knowledge gained from patterns and their representation. In this technique, labeled training data is used to train pattern recognition systems.
Pattern Matching works by "reading" through text strings to match patterns that are defined using Pattern Matching Expressions, also known as Regular Expressions. Pattern Matching can be used in Identification as well as in Pre-Classification Processing, Page Processing, or Storage Processing.
Python and Elixir Programming Bundle Course Pattern matching is a technique which Elixir inherits form Erlang. It is a very powerful technique that allows us to extract simpler substructures from complicated data structures like lists, tuples, maps, etc. A match has 2 main parts, a left and a right side.
To use your example:
def func(p1, p2 \\ 2, p3 \\ 3, p4) do
IO.inspect [p1, p2, p3, p4]
end
If you compile your code and type h DefaultParams.func
with tab
, it will show you
iex> h DefaultParams.func
func/2 func/3 func/4
It actually created 3 functions for you.
def func(p1, p4), do: func(p1, 2, 3, p4)
def func(p1, p2, p4), do: func(p1, p2, 3, p4)
def func(p1, p2, p3, p4) do
IO.inspect [p1, p2, p3, p4]
end
iex> func(:a, :b) # calling func/2, which is actually func(p1, 2, 3, p4)
[:a, 2, 3, :b]
iex> func(:a, :b, :c) # calling func/3, which is actually func(p1, p2, 3, p4)
[:a, :b, 3, :c]
iex> func(:a, :b, :c, :d) # calling func/4
[:a, :b, :c, :d]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With