Aetherus

Aetherus

Destructing assignment

I want to mimic ES6’s destructing assignment using Elixir’s sigil.

What I want to achieve is

~m{foo bar} = %{foo: 1, bar: 2}
foo  #=> 1
bar  #=> 2

So far I have the following code

defmodule DestructingAssignment do
  defmacro __using__(_) do
    quote do: import unquote(__MODULE__)
  end

  defmacro sigil_m({:<<>>, _line, [string]}, []) do
    spec = string
           |> String.split
           |> Stream.map(&String.to_atom/1)
           |> Enum.map(&{&1, {&1, [], Elixir}})  #=> [foo: {:foo, [], Elixir}, bar: {:bar, [], Elixir}]
    {:%{}, [], spec}
  end
end

When I run ~m{foo bar} = %{foo: 1, bar: 2}, pattern matching succeeds. But when I try to read the variable foo, it gives me

warning: variable "foo" does not exist and is being expanded to "foo()", please use parentheses to remove the ambiguity or change the variable name
  iex:9

** (CompileError) iex:9: undefined function foo/0

I guess this is due to the macro hygiene, but as you can see, the sigil implementation doesn’t use quote. How can I inject local variable to the macro’s caller’s scope?

Most Liked

matteosister

matteosister

kip

kip

ex_cldr Core Team

I think just one small change is required:

defmodule DestructingAssignment do
  defmacro __using__(_) do
    quote do: import unquote(__MODULE__)
  end

  defmacro sigil_m({:<<>>, _line, [string]}, []) do
    spec = string
           |> String.split
           |> Stream.map(&String.to_atom/1)
           |> Enum.map(&{&1, {&1, [], nil}})  #=> [foo: {:foo, [], nil}, bar: {:bar, [], nil}]
    {:%{}, [], spec}
  end
end
Aetherus

Aetherus

Works like a charm! But here come a new question, what does the last part of an AST node mean?

taiansu

taiansu

According to Saša Jurić’s article about macros, the third part of variable AST represents where the quoting happens. If it’s nil, the identifier is not hygienic. Check out paragraph “Discovering the AST structure” of the article and the series for the detail.

KristerV

KristerV

I have no ideas how macros work, but this is very useful and I made a string version also:

  defmacro sigil_d({:<<>>, _line, [string]}, []) do
    spec =
      string
      |> String.split()
      |> Stream.map(&String.to_atom/1) # how could we do without this?
      |> Enum.map(&{to_string(&1), {&1, [], nil}})

    {:%{}, [], spec}
  end

Works great! (so far)

iex(31)> ~d(a) = %{"a" => 5}
%{"a" => 5}
iex(32)> a
5

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New

Other popular topics Top

yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure 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
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New

We're in Beta

About us Mission Statement