Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I used matched arguments in elixir functions

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!

like image 336
Joel Jackson Avatar asked Mar 23 '16 16:03

Joel Jackson


People also ask

What is pattern matching in Elixir?

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.

How do you call a function in Elixir?

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.

What is lot pattern matching?

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.

What is pattern matching in programming?

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.


1 Answers

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})
like image 184
Gazler Avatar answered Oct 14 '22 09:10

Gazler