Chapter 13. Using Macros to Extend Elixir

Étude 13-1: Atomic weights

In this étude, you will create a macro that will create a set of functions whose names are the symbols for the elements (all lowercase, as Elixir does not allow a function name to start with an uppercase letter). These functions take no arguments and return the atomic weight of the element, rounded to three decimal places. Thus, your macro will do the moral equivalent of creating functions like these:

def h() do
  1.008
end

def he() do
  4.003
end

Here is a list of the first 26 elements in a form that may be useful to you.

[{:h, 1.008}, {:he, 4.003},
 {:li, 6.94}, {:be, 9.012}, {:b, 10.81}, {:c, 12.011},
 {:n, 14.007}, {:o, 15.999}, {:f, 18.998}, {:ne, 20.178},
 {:na, 22.990}, {:mg, 24.305}, {:al, 26.981}, {:si, 28.085},
 {:p, 30.974}, {:s, 32.06}, {:cl, 35.45}, {:ar, 39.948},
 {:k, 39.098}, {:ca, 40.078}, {:sc, 44.956}, {:ti, 47.867},
 {:v, 50.942}, {:cr, 51.996}, {:mn, 54.938}, {:fe, 55.845}]

You don’t need to make a complete list of all 92 basic elements unless you feel especially ambitious; the purpose of this étude is to use macros, not to learn chemistry.

Write one module named AtomicMaker that has the defmacro in it, and another module named Atomic that will require AtomicMaker.

Once you have this, you will be able to calculate the atomic weights of molecules:

iex(1)> c("atomic_maker.ex") [AtomicMaker] iex(2)> c("atomic.ex") [Atomic] iex(3)> import Atomic nil iex(4)> water = h * 2 + o 18.015 iex(5)> sulfuric_acid = h * 2 ...

Get Études for Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.