vic

vic

Asdf Core Team

Expat - composable, reusable pattern matching

Expat is a tiny experiment I did for extracting patterns and being able to reuse them (compose and share patterns between elixir libraries). Look for zombies in the README.

It was born as some of my first attempts at creating composable things like the just released data specification library Spec.

Hope anyone finds it interesting at least.

Most Liked

josevalim

josevalim

Creator of Elixir

This is a really nice project. Since you are exploring things on the area, here are some challenges/questions you can consider:

  1. Is it possible to extend expat to be a generalization of records? defpat contains an exact subset of the records functionality, which is the pattern matching one. It is also easy to see how defpat could be used for updates, all you need to do is to match on the value and then build another new value of exactly the same shape with the same variables in place except the ones you are replacing, etc.

  2. Have you considered using another operator instead of = for mixing patterns? I believe your mixing of patterns is actually an intersection. If you assume that %{"id" => id} will match all maps with the "id" field, including %{"id" => "foo", "name" => "baz"}, and the pattern %{"name" => name} all maps with a "name" field, including the map mentioned above, when you specify id() = name() you are actually saying it should have BOTH patterns, id() AND name(). If you think of patterns as sets representing the structures they can match on, it is an intersection. Another reason to choose another operator is that the precedence will work in a way it won’t require parentheses, for example: defpat subject id() &&& name(). Here is a list of operators.

There is one feature we could add to Elixir that would allow the library to become more powerful which is to allow guards inside patterns:

def is_foo_or_bar(atom when atom in [:foo, :bar])

Of course nobody would write such in practice but supporting it would allow you to express patterns with guards:

def is_foo_or_bar(foo_or_bar())

Which the Elixir compiler would then rewrite internally as:

def is_foo_or_bar(atom) when atom in [:foo, :bar]

Anyway, this is very exciting and it is close to topics I am currently researching. :slight_smile: I could expand more on both points above if you are interested. For example, if you are able to generalize defpat to records, you should also be able to generalize it for map updates, and if you define a pattern such as:

defpat foo_bar_baz %{"foo" => {bar, baz}}

And then allow someone to update the nested tuple like this:

map = %{"foo" => {1, 2}, "hello" => "world"}
foo_bar_baz(map, bar: 3)
#=> %{"foo" => {3, 2}, "hello" => "world"}

Optimizations could allow you to compile foo_bar_baz to %{map | "foo" => Map.fetch!(map, "foo") |> put_elem(0, 3)}.

vic

vic

Asdf Core Team

Hey, good news, I’ve just released v1.0, I did a major rewrite as I really wanted (and needed) it to support guards. Wrote much a much better README guide (I guess) and also documented it more.

The only thing I removed from v0 is the ... syntax as it introduced all variables in scope and it was mostly a pain since elixir 1.5. So now you have to be explicit on what you bind.

Hope the guide explains a bit better where this library fits and how it could be used.

<3

Edit. Forgot to mention, for @josevalim, in the example using guards from the readme, expat def just expands the inner patterns and collects (anding) any guards produced by them, and finally just ands those with any from the function definition. here’s the code

ibgib

ibgib

Yeah, this is definitely my favorite new library. The primary gain from it for me is making things DRYer. Where before I would have map structures repeated in multiple function clauses, e.g.

def handle_cmd(%{"dest_ib" => dest_ib,
                 "context_ib_gib" => context_ib_gib,
                 "src_ib_gib" => src_ib_gib} = data, ..) when guard1 do
def handle_cmd(%{"dest_ib" => dest_ib,
                 "context_ib_gib" => context_ib_gib,
                 "src_ib_gib" => src_ib_gib} = data, ..) when guard2 do

which has redundancy in the "var_name" => var_name, as well in the function clause level. And dest_ib and src_ib_gib are used across multiple commands in many places. I’m now able to create a single file for the reused patterns:

defmodule WebGib.Patterns do
  @moduledoc """
  Reusable patterns using expat
  """
  
  import Expat
  
  defpat dest_ib_        %{"dest_ib" => dest_ib}
  defpat src_ib_gib_     %{"src_ib_gib" => src_ib_gib}
  defpat context_ib_gib_ %{"context_ib_gib" => context_ib_gib}
  # ..
end

(NB: I am tacitly going with a _ suffix to indicate a pattern vs the var name, but I’m not sure what other non-word characters are legal in elixir. I would rather prefix the pattern with a single character and would love any suggestions.)

And then I compose them above the function and consume them:

defpat fork_data_(
  dest_ib_() =
  context_ib_gib_() =
  src_ib_gib_()
)

def handle_cmd(fork_data_(...) = data, ..) when guard1 do
def handle_cmd(fork_data_(...) = data, ..) when guard1 do

EDIT: The ... inside the pattern is literal syntax, which helps enormously with DRY. The other .. just means other args.

This is ridiculously more DRY and readable. Definitely a powerful lib you made here! :smile:

Thank you! :thumbsup:

Where Next?

Popular in Announcing Top

martinthenth
Hello everybody :wave: Recently, some of my colleagues talked about database ids and uuids and their problems, and I remembered the pain...
New
josevalim
EDIT: since Ecto 3.0 final version is out, this post was amended to use the final versions in the instructions below. Hi everyone, We a...
New
mtrudel
Bandit is an HTTP server for Plug and WebSock apps. Bandit is written entirely in Elixir and is built atop Thousand Island. It can serve...
New
kip
ex_cldr provides localisation and internationalisation support based upon the data from the Unicode CLDR project. Unicode released CLDR ...
407 12840 120
New
type1fool
WebAuthnLiveComponent WebAuthnComponents See this post about renaming the package. Passwordless authentication for Phoenix LiveView app...
New
hpopp
After just over two years in development, this latest version of Pigeon is what I finally consider done in regards to my original vision ...
New
benlime
LiveMotion enables high performance animations declared on the server and run on the client. As a follow up to my previous thread A libr...
New
markmark206
simple_feature_flags is a tiny package that lets you turn features on or off based on which environment (e.g. localhost, staging, product...
New
scohen
Lexical Lexical is a next-generation language server for the Elixir programming language. Features Context aware code completion As-you...
New
mattludwigs
Grizzly is a library for working with Z-Wave devices. Z-Wave is a low-frequency radio protocol for controlling smart home devices on a me...
New

Other popular topics Top

skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
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
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52341 488
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
marick
I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I’m a nov...
New

We're in Beta

About us Mission Statement