Book Image

Learning Elixir

By : Kenny Ballou, Kenneth Ballou
Book Image

Learning Elixir

By: Kenny Ballou, Kenneth Ballou

Overview of this book

Elixir, based on Erlang’s virtual machine and ecosystem, makes it easier to achieve scalability, concurrency, fault tolerance, and high availability goals that are pursued by developers using any programming language or programming paradigm. Elixir is a modern programming language that utilizes the benefits offered by Erlang VM without really incorporating the complex syntaxes of Erlang. Learning to program using Elixir will teach many things that are very beneficial to programming as a craft, even if at the end of the day, the programmer isn't using Elixir. This book will teach you concepts and principles important to any complex, scalable, and resilient application. Mostly, applications are historically difficult to reason about, but using the concepts in this book, they will become easy and enjoyable. It will teach you the functional programing ropes, to enable them to create better and more scalable applications, and you will explore how Elixir can help you achieve new programming heights. You will also glean a firm understanding of basics of OTP and the available generic, provided functionality for creating resilient complex systems. Furthermore, you will learn the basics of metaprogramming: modifying and extending Elixir to suite your needs.
Table of Contents (16 chapters)
Learning Elixir
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Context and macro hygiene


Since macros are about injecting code, special care must be taken for the context, of both the caller and the context of the macro. The injected code of the macro cannot safely assume that certain variables will be available for it to consume. For example, let's look at a macro definition that attempts to access some variables of the caller context:

defmodule ContextInfo do
  defmacro grab_caller_context do
    quote do
      IO.puts x
    end
  end
end

Load up this module in iex:

iex(1)> c "context.exs"
[ContextInfo]
iex(2)> import ContextInfo
nil
iex(3)> x = 42
42
iex(4)> grab_caller_context
** (CompileError) iex:4: undefined function x/0
    expanding macro: ContextInfo.grab_caller_context/0
    iex:4: (file)

After importing and binding a variable, invoking the macro yields a compiler error, as we would expect, because the macro cannot implicitly access the caller's context.

Similarly, the macro cannot safely inject code that changes the context or environment...