Say I have two use cases for a function. Do something with users that have a subscription and something with users that don't have a subscriptions.
def add_subscription(subscription_id, %User{subscription: nil})
# Do something with user here.
And
def add_subscription(subscription_id, user)
How do I do pattern matching like this and also still use the user in the first function?
Thanks!
Pattern matching allows developers to easily destructure data types such as tuples and lists. As we will see in the following chapters, it is one of the foundations of recursion in Elixir and applies to other types as well, like maps and binaries.
In order to call a function in Elixir we want to use the module name, in this case 'Calculator', and then the function we want to invoke, we'll use squared here. And pass in any arguments the function expects. Great all the functions from our Calculator module returned the values we expected.
Pattern matching is the act of checking one or more inputs against a pre-defined pattern and seeing if they match. In Elm, there's only a fixed set of patterns we can match against, so pattern matching has limited application.
Pattern matching in computer science is the checking and locating of specific sequences of data of some pattern among raw data or a sequence of tokens. Unlike pattern recognition, the match has to be exact in the case of pattern matching.
You can bind the function argument to a variable:
def add_subscription(subscription_id, %User{subscription: nil} = user)
The convention is to assign after the pattern match:
# Do This
def foo(%User{subscription: nil} = user)
# Instead of this
def foo(user = %User{subscription: nil})
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