Crowdhailer

Crowdhailer

Creator of Raxx

Semantic pattern matching, useful or not?

It is rare to use direct calls to send in elixir. The call is normally wrapped in a function which is responsible for sending the correct message. The most common example of this has to be GenServer.call. This is seen as good practice as it allows the structure of the message to be hidden. The structure of the message being an implementation detail only.

However when receiving a message or pattern matching the internal details must always be known. At least this is certainly true in erlang but does not need to be true in Elixir because it has macros.

The most simple case I can think of is the convention of using {:ok, value} || {:error, reason}. This is an implementation of how a function can indicate it has succeeded or failed. It would be possible to use another convention for example %Try.Success{value: value} || %Try.Failure{reason: reason}. To hide which implementation is being used macros can be employed. E.g in a case statement. (The same is true in a receive block).

For example.

case my_func() do
  {:ok, value} ->
    # continue
  {:error, reason} ->
    # report error
end

can be replaced with what I call “semantic pattern matching”

case my_func() do
  success(value) ->
    # continue
  failure(reason) ->
    # report error
end

An implementation of the success and fail macros is available in my OK project.

I will admit that the extra value in this case might not be very high. The example of :ok/:error tuples is both simple and common knowledge. However I think it could be very useful in a few cases, for example.

  • When a process could receive messages from two different libraries. e.g. a Gen server that is running taskes. It might receive a call message or a message notifying of a completed task.
  • A finite statemachine that is receiving commands to change state.

Most Liked

josevalim

josevalim

Creator of Elixir

For what is worth, this is a question I frequently ask myself: if it is worth adding abstractions on top of pattern matching and provide conveniences such as defpattern and/or defguard? It is one of those things I am somewhat glad the Erlang VM restrict us from generalizing because we would probably have done so some time ago and the solution may not have been ideal.

Maybe one day we will add something that resembles discriminated unions and named patterns, which would give the features you described above, but right now there are still many questions around on how to generalize such patterns while providing good performance and sane semantics. The current mechanism, although it may be repetitive some times, it is simple, explicit and straight-forward. See the expat thread for a similar discussion.

11
Post #4
X4lldux

X4lldux

I’ve created a library for doing exactly this, called disc_union. For your example it would look like this:

defmodule Result do
  use DiscUnion

  defunion :ok in any() | :error in atom
end

defmodule Example do
   use Result

   def foo() do
     Result.case my_func() do # expects a %Result{} struct
       :ok in value -> #continues
       :error in reason -> #report the error
     end
   end
end

NOTE: you can also “import” a regular error tuple into the Result struct using Result.from!/1 function and it will check if what your are importing was defined as one of the variants.

Downside is that for each discriminated union there has to be a specially created case macro, in order for it to “know” what valid variants are in this union and warn you (at compile time) when you miss one or implement it with a wrong shape. I find it very useful and use it in production even though I still consider this a research project.

Qqwy

Qqwy

TypeCheck Core Team

I believe that if your patterns become too complex in a single function, then that might be a very clear indicator that that function could be split in smaller parts.

I do like pattern-matching extensively to ensure that people know it right away when they put garbage in my libraries’ functions. Sometimes these matches become relatively long. I have been tempted to fiddle with pattern-providing macros before, but have not gone through with it until now because I also believed that this would make it harder to read what was going on. I think there are some use cases where you frequently want to match a struct that is in a certain state.

I agree with @josevalim and @crowdhailer: This is not something Elixir itself should provide, but it is great that we can, if it turns out to be useful for the project at hand, write macros that do this stuff.

Where Next?

Popular in Discussions Top

blackode
Elixir Upgrading is so Simple in Ubuntu and It worked for me Ubuntu 16.04 git clone https://github.com/elixir-lang/elixir.git cd elixir...
New
jeramyRR
This is an interesting article to read. Elixir’s performance, like usual, is excellent. However, it seems like the high CPU usage is co...
New
thojanssens1
It would be nice to be able to define a redirect from one route to another from the router.ex file. E.g.: redirect "/", UserController, ...
New
praveenperera
How We Replaced React with Phoenix By: Thought Bot
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
hazardfn
I suppose this question is effectively hackney vs. ibrowse but we are at a point in our project where we have to make a choice between th...
New
PragTob
Hey everyone, this has been on my mind for some time and I’d love your input on it! TLDR: I feel like maps are superioer for storing and...
New
eteeselink
Hi all, In the last days, two things happened: A blog post titled “They might never tell you it’s broken” made the rounds. It’s about ...
New
restack_oslo
Hello, Please pardon me for any faux paux. I am 46 and this is my first time on a forum of any kind. I wanted to to get answers from tho...
New
AstonJ
Can you believe the first professionally published Elixir book was published just 8 years ago? Since then I think we’ve seen more books f...
New

Other popular topics Top

AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
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
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
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
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