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
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
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
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.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









