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.

JohnnyCurran

JohnnyCurran

Elixir will only show the line number of the first defined function head (on a FunctionClauseError). It will also log each function head it attempted to take - if each function head is unwrapping several values that are orthogonal to the flow control, it becomes difficult to tell which one should have been taken.

That leaves the developer in the unfortunate position of figuring out

  1. Which function head should have been taken with this call?
  2. Which missing value caused this function invocation to fail?
JohnnyCurran

JohnnyCurran

I understand and I do empathize. I often find myself wanting to unwrap everything in the function head. I’ve found, however, after over 4 years of production elixir, that it causes more problems than it solves

in particular, how do you square:

function head pattern matching is an all-or-nothing

with:

When the sizes are manageable it’s very easy to tell which function head was attempted

At a certain point, especially on a team, the sizes of parameters are going to get large. It’s inevitable. is it all-or-nothing, or is it a manageable size?

And, to be honest I’m not sure I totally understand this question:

Why do we get FunctionClauseError at this non-early stage of the project still

If you are suggesting we all write error-free code, I agree, but I don’t know how practical that is. FunctionClauseErrors aren’t exclusive to third-party apis, and, like everything in software – things change. To suggest “just don’t write code that throws a FunctionClauseError” seems misled

In any case – I have genuinely enjoyed this discussion with you as I love discussing the ins-and-outs of Elixir with whoever is unfortunate enough to be within earshot :slight_smile: , especially so with those whom which I disagree. There is no growth without disagreement. All that to say that I hope my tone has not come off as disrespectful which I know it has the possibility to do over text, especially over the wider internet :slight_smile:

Where Next?

Popular in Questions Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
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
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New

Other popular topics Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement