Skip to content

Instantly share code, notes, and snippets.

@manpages
Last active March 13, 2016 17:47
Show Gist options
  • Save manpages/4582318 to your computer and use it in GitHub Desktop.
Save manpages/4582318 to your computer and use it in GitHub Desktop.
Elixir Newbie Digest, Issue #1

Intro

I have finally decided to start "Elixir newbie digest" and put here stuff that would be nice for me to understand before I have started my first Elixir production project.

Some of those will be hints, some of those will be in depth analysis of how Elixir language deals with stuff, but I plan to focus on the very basic things and keep those digests as much practical as possible.

Don't know whether those digests will be periodic, but I sincerely hope so.

Dotted function invocation

Don't forget dot when invoking a function stored in a variable

iex(1)> f = 1+&1
#Fun<erl_eval.6.82930912>

iex(2)> f(41)
** (UndefinedFunctionError) undefined function: IEx.Helpers.f/1

iex(2)> f.(41) # note the dot
42

Oneliners

If you want to one-line some definition, such as function definition, use , do: body syntax, where body is the body of your function. In fact, this is how Elixir treats your do ... end blocks (you'll get why there is comma before do: later), observe:

iex(8)> quote(do: defmodule SomeName do :ok end) == quote(do: defmodule SomeName, do: :ok)
true
iex(9)> quote(do: defmodule SomeName do :ok end)                                          
{:defmodule,0,[{:_aliases_,0,[:SomeName]},[do: :ok]]}

But wait, there is more! Let's reverse the logic: anything that takes [do: block] can be "multilined" as follows:

iex(21)>   f = function do
...(21)>    (do: anything) -> anything
...(21)>    (_) -> :nothing
...(21)>   end
#Fun<erl_eval.6.82930912>
iex(22)> f.() do
...(22)>  the_answer = 42
...(22)>  the_answer
...(22)> end
42
iex(23)> f.(do: "works")
"works"
iex(24)> f.([do: "also works"])
"also works"

Now let's explain the strange comma before do:

iex(25)> quote(do: defmodule SomeName, do: :ok) == quote(do: defmodule(SomeName, do: :ok))
true

as you can see, that simply is the result of Elixir being able to handle parensless syntax! Also note that:

iex(27)> quote(do: defmodule(SomeName, do: :ok)) == quote(do: defmodule(SomeName) do :ok end)
true

And a hint from Mr. José Valim — "in general, everything in between do…end can be written as do: (…)", observe:

iex(31)> defmodule(ILoveParens, do: (
...(31)>   def(my_favorite_chars, do: (
...(31)>    "My favorite characters are '(' and ')'."
...(31)>   ))
...(31)> ))

That's it for today.

So long, and thanks for all the reading.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment