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.

First Post!

OvermindDL1

OvermindDL1

Huh, looks to save a lot on readability. Is it mostly just for maps?

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:

Last Post!

marciol

marciol

I’m thinking that expat can be a simple way to improve readability and also it allows a way to do a sort of contract check at function boundaries. Is this the way to follow or the Elixir community are agreeing on other approaches?

Where Next?

Popular in Announcing Top

tmbb
I’ve published the first version of my Makeup library. It’s a syntax highlighter for Elixir in the spirit of Pygments, Currently it highl...
New
mspanc
I am pleased to announce an initial release of the Membrane Framework - an Elixir-based framework with special focus on processing multim...
New
josevalim
Hi everyone, We would like to announce that Plataformatec is working on a new MySQL driver called MyXQL. Our goal is to eventually integ...
New
mindok
What is ContEx? A pure Elixir server-side data plotting/charting library outputting SVG. It has nice barcharts in particular and works g...
New
trisolaran
Hi! :waving_hand: I would like to present LiveSelect, a little library that I wrote to easily add a dynamic selection input to your LV f...
198 11241 107
New
type1fool
WebAuthnLiveComponent WebAuthnComponents See this post about renaming the package. Passwordless authentication for Phoenix LiveView app...
New
zachdaniel
Ash Framework What is Ash? Ash Framework is a declarative, resource-oriented application development framework for Elixir. A resource can...
New

Other popular topics Top

hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 54996 245
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
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
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

We're in Beta

About us Mission Statement