sodapopcan

sodapopcan

Can someone explain `do` syntax in a non hand-holding way?

I’m wondering exactly what a do block is.

Is it a closure? Is it a procedure? Is it an anonymous function? Is it a lambda? Is it something else?

Is it more useful to think of an Elixir do block as a Ruby block or as Haskell’s do notation or maybe a combination of the two? Or neither!!? Maybe even a JS closure?

Is it some mutant variation of all of that?? Or maybe none of that!???

I do (haha, get it?) have some intuition about this and have read the meta-programming part of the Elixir guides (which calls it an expression but, like, it’s really a series of expressions… no?) and I’m just looking for some insightful—or even just fun—responses from people in the community, if anyone is willing.

What I already think I know:

  • do is syntactic sugar for calling the, uh, “block of code” provided to the :do key of a keyword list arg provided to a macro
  • That’s it!

Thank you!!

Most Liked

josevalim

josevalim

Creator of Elixir

In a nutshell, do-end blocks is a syntax sugar for a :do keyword list.

if CONDITION do
  EXPR
end

is the same as:

if CONDITION, do: (EXPR)

You can see this by calling quote as shown by @ityonemo. Since keyword lists are just data structures, do-blocks end-up being just data structures too. It doesn’t need to be given only to macros, regular functions can also use and match on it, some helpers in Phoenix.HTML do so, but their usage is indeed more common with macros.

As a syntax sugar, they also allow some specific syntactical constructs, such as left -> right and other keywords (else, rescue, etc), but all of them can be written in the literal keyword syntax format too.

ityonemo

ityonemo

haha maybe I think I should break this down more carefully. A macro in elixir is a function that emits AST + “take the AST generated, right here in the code” (a bare function will drop its value, in that location, not the AST). So macros in the first are a function. Let’s consider the “def” macro.

We’ll look at it three ways:

quote do
  def foo, do: :bar 
end

which yields:

{:def, [context: Elixir, import: Kernel],
 [{:foo, [context: Elixir], Elixir}, [do: :bar]]}

and

quote do
  def foo do
     :bar
  end
end

which yields

{:def, [context: Elixir, import: Kernel],
 [{:foo, [context: Elixir], Elixir}, [do: :bar]]}

and

quote do
  def foo do
     :throwaway_statement
     :bar
  end
end 

which yields

{:def, [context: Elixir, import: Kernel],
 [
   {:foo, [context: Elixir], Elixir},
   [do: {:__block__, [], [:throwaway_statement, :bar]}]
 ]}

Note a) forms 1 and 2 are identical
and b) form 3 groups the two lines of the function into a block.

Why is that necessary? Because according to Kernel.def/2 documentation (https://hexdocs.pm/elixir/Kernel.html#def/2), the function half of the def macro must take TWO AST parameters. The first parameter is the name of the function (and also a list of arguments) and the second parameter is the contents of the function. So the only arity-consistent way of representing def is by grouping the AST for the body of the function into a block and labeling it as “do”. So the do “keyword” is just elixir’s cute way of saying "hey everything until the “end” keyword winds up in the block. And if you don’t want a block, you can just pass it as do:, which builds the keyword list manually and passes it into the def function without syntactic sugar.

One more important thing to note is that in elixir, lists, atoms, and two-tuples don’t need escaping, because they are identical to their AST, so that’s how when you do a one-liner the do: part of the code makes it into the macro without being converted into these strange tuple forms.

as for why it’s a keyword list, if you look further down the documentation, you can have other parts to the function code, for example catch or rescue blocks; if you do that, for example this code which is nonsensical:

quote do
  def foo do
     :bar
   catch
     :baz
   end
end

yields:

{:def, [context: Elixir, import: Kernel],
 [{:foo, [context: Elixir], Elixir}, [do: :bar, catch: :baz]]}

so other “segments” of the function can nicely wind up stuffed into an arity-2 statement. Likewise you can arbitrarily mix-and-match catches and rescues, because a keyword-list is what you are supposed to use when you have a maybe-ordered list of arbitrary things that can’t be a map because you can maybe have duplicates.

ityonemo

ityonemo

Just tried it. Mind blown. I mean, of course, what was I thinking, why wouldn’t that work??!. I promise not to use this power for evil.

Where Next?

Popular in Questions Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
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
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
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
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
Mooodi
Given a string, how can I get access to its character by index? Enum.at("my_string", 2) doesn't work. Or rather, not char, but a substr...
New
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
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

Other popular topics Top

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
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
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
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New

We're in Beta

About us Mission Statement