OvermindDL1

OvermindDL1

Defguard - experimenting with a structural matching alternative to Kernel.defguard

There is a talk about defguard at Provide defguard · Issue #2469 · elixir-lang/elixir · GitHub and I was curious to see if I could make a defguard powerful enough to implement an is_struct (which requires altering the matching context as well as altering guards). Well I made it, it is a hack, it is simple, would neeed more cleaning up before release if I should release it (unsure if I should) considering the hack that it is, but it works. :slight_smile:

A shell session:

blah@blah MINGW64 $HOME/projects/tmp/defguard
$ iex -S mix
Eshell V8.2  (abort with ^G)
Interactive Elixir (1.4.0) - press Ctrl+C to exit (type h() ENTER for help)
iex>defmodule StructEx do
...>   import Defguard
...>   defguard is_struct(%{__struct__: struct_name}) when is_atom(struct_name)
...> end
{:module, StructEx,
 <<70, 79, 82, 49, 0, 0, 5, 252, 66, 69, 65, 77, 69, 120, 68, 99, 0, 0, 0, 155,
   131, 104, 2, 100, 0, 14, 101, 108, 105, 120, 105, 114, 95, 100, 111, 99, 115,
   95, 118, 49, 108, 0, 0, 0, 4, 104, 2, ...>>, {:is_struct, 1}}
iex> defmodule Testering do
...>   use Defguard
...>   import StructEx
...>   def blah(any_struct) when is_struct(any_struct), do: any_struct
...>   def blah(_), do: nil
...> end
warning: unused import StructEx
{  iex:4
:module
, Testering,
 <<70, 79, 82, 49, 0, 0, 5, 24, 66, 69, 65, 77, 69, 120, 68, 99, 0, 0, 0, 151,
   131, 104, 2, 100, 0, 14, 101, 108, 105, 120, 105, 114, 95, 100, 111, 99, 115,
   95, 118, 49, 108, 0, 0, 0, 4, 104, 2, ...>>, {:blah, 1}}
iex> Testering.blah(%{__struct__: Blah})
%{__struct__: Blah}
iex> Testering.blah(%{blah: 42})
nil
iex> Testering.blah(42)
nil
iex>

As you can see, it works fine. ^.^

I’m also playing with the idea to have defguard accept an optional do/end so it can do compile-time checks and alter the ast directly, but not needed for something as simple as is_struct/1. :slight_smile:

My hack is ‘just’ implemented enough for something this simple to work, would need work to have more, but considering it is less than 60 lines of code to do what I have now and adding more cases is easily expressed with how I have things split up, this could easily become a full defguard hack^H^H^H^Himplementation. ^.^

Overall it has code that makes a new function head internally for each new when condition with the body for each, basically what erlang does internally anyway with multiple whens, just explicit, so it should not have any speed hit over doing it manually (plus multiple whens on a function head is almost never used), just it is much less code this way. But yeah, defining an is_exception would be as simple as:

defguard is_exception(%{__struct__: struct_name, __exception__: true}) when is_atom(struct_name)

And this has the same checking power as Exception.exception?/1 does that is in Elixir now, except it works as a guard, like:

iex> defmodule StructEx do
...>   import Defguard
...>   defguard is_exception(%{__struct__: struct_name, __exception__: true}) when is_atom(struct_name)
...> end
{:module, StructEx,
 <<70, 79, 82, 49, 0, 0, 6, 48, 66, 69, 65, 77, 69, 120, 68, 99, 0, 0, 0, 158,
   131, 104, 2, 100, 0, 14, 101, 108, 105, 120, 105, 114, 95, 100, 111, 99, 115,
   95, 118, 49, 108, 0, 0, 0, 4, 104, 2, ...>>, {:is_exception, 1}}
iex> defmodule Testering do
...>   use Defguard
...>   import StructEx
...>   def blorp(exc) when is_exception(exc), do: "exceptioned"
...>   def blorp(val), do: "No-exception:  #{inspect val}"
...> end
{  iex:5
:module
, Testering,
 <<70, 79, 82, 49, 0, 0, 6, 52, 66, 69, 65, 77, 69, 120, 68, 99, 0, 0, 0, 148,
   131, 104, 2, 100, 0, 14, 101, 108, 105, 120, 105, 114, 95, 100, 111, 99, 115,
   95, 118, 49, 108, 0, 0, 0, 4, 104, 2, ...>>, {:blorp, 1}}
iex> Testering.blorp(42)
"No-exception:  42"
iex> Testering.blorp(%{__struct__: Blah})
"No-exception:  %{__struct__: Blah}"
iex> Testering.blorp(%ArithmeticError{})
"exceptioned"
iex>

So does this seem useful enough to release even if it is a hack? Does anyone else want to work on it since I am very short on time for at least the next few weeks? ^.^

Most Liked

Eiji

Eiji

I’m really waiting for feature like that. It will be really usefull in full version. Please continue work on it.

OvermindDL1

OvermindDL1

Elixir is already working on a Kernel.defguard as linked in the first post, but as it is a macro and not a special syntax it will not have the capabilities that this one does, and would not quite match. Perhaps I should rename mine defpattern instead, hmm…

What Elixir should do is make its defguard actually powerful instead of just being an overglorified macro that we can already easily do. Like the current elixir proposal just implements is_record as:

  defguard is_record(data, kind) when
    is_atom(kind) and is_tuple(data) and tuple_size(data) > 0 and elem(data, 0) == kind

When we can already do it as a macro, as the original version is, so it is not adding any new functionality where my above version actually does (though my implementation is definitely as a hack, it ‘should’ be as syntax).

Where Next?

Popular in Announcing Top

wmnnd
Hi there, for my project DBLSQD, I needed a file storage solution that is a bit more flexible than Arc. Because I thought others might f...
New
tmbb
PhoenixWS - Websockets over Phoenix Channels Source code on Github here: GitHub - tmbb/phoenix_ws: Websockets implemented over Phoenix Ch...
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
gabrielpoca
Hello everyone! I want to share with you something that I’m really proud of: https://stillstatic.io/ Still is a static site builder for...
New
devonestes
Introducing assertions, the library that helps you write really great test assertions! GitHub: GitHub - devonestes/assertions: Helpful a...
New
maltoe
Hello! Came here to announce ChromicPDF, a pet project PDF generator I’ve been working on for the past few months. Why another PDF gener...
New
type1fool
WebAuthnLiveComponent WebAuthnComponents See this post about renaming the package. Passwordless authentication for Phoenix LiveView app...
New
Hal9000
Here is my first stab at this. README pasted below. https://github.com/Hal9000/elixir_random Comments and critiques are welcome. Thank...
New
zoltanszogyenyi
Hey everyone :waving_hand: Excited to join this forum - I am one of the founders and current project maintainers of a popular and open-s...
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 10858 107
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
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
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
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39297 209
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 47930 226
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

We're in Beta

About us Mission Statement