gameline

gameline

What is the best pattern matching function's arguments or in function's body?

Hi,
I was surprised I couldn’t find any argument on this on the net so here I am.

When you make recursive function that deal with list and want to pattern match argument against [] or [head|tail] you can:

function [], do: *something*
function [h|t], do: *something else*

which is what I would call the Elixir way. A more haskellish way might be:

function argument do
  case argument []
    [] -> something()
    [h|t] -> something_else()
  end
end

The first option allow you to handle different arities the same way but is there other good arguments on why you should use the first option instead of the second ?

Most Liked

rvirding

rvirding

Creator of Erlang

It makes no difference at all with regards to efficiency. Literally the complier translates it into almost the same code with the main difference being what error you will get.

JohnnyCurran

JohnnyCurran

Yes, precisely, and I think a good example that may illustrate what I’m trying to say a little better may be –

Let’s consider for a moment that my app is capable of communicating with Google Bard as well as OpenAI,

My LiveView may make a function call like this:

MyContext.complete_chat%{messages: messages, ai_service: :open_ai})

In my context, I unwrap only what’s necessary to determine which function head to take:

def complete_chat(%{ai_service: :open_ai} = attrs) do
  %{messages: messages} = attrs
  # call openai api here
end

def complete_chat(%{ai_service: :google_bard} = attrs) do
  %{messages: messages} = attrs
  # call google bard here
end

MatchErrors now point me directly to the specific function head where the error occurred

JohnnyCurran

JohnnyCurran

Pattern matching in the function head should be used for flow control.

Pattern matching in the body of the function should be “this function requires this data”

It’s a subtle but important distinction.

Yes MatchError is better than FunctionClauseError, especially in the case where you have multiple function heads. It is much easier to jump to the line number of the MatchError than it is to figure out which function head is missing an assign in a large assigns crash dump.

Where Next?

Popular in Questions Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
New
vac
Hi, I’m quite new in Elixir and I’m trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and I...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: <h1>Create Post</h1> <%= ...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 127089 1222
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 48342 226
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement