Chapter 22
Exercise: MacrosAndCodeEvaluation-1
defmodule My do
defmacro myunless(condition, clauses) do
do_clause = Keyword.get(clauses, :do, nil)
else_clause = Keyword.get(clauses, :else, nil)
quote do
if unquote(condition) do
unquote(else_clause)
else
unquote(do_clause)
end
end
end
end
defmodule MyTest do
require My
My.myunless(1 == 2, do: IO.puts("1 != 2"), else: IO.puts("1 == 2"))
end
Exercise: MacrosAndCodeEvaluation-2
defmodule Times do
defmacro times_n(n) do
quote do
def unquote(String.to_atom("times_#{n}"))(m) do
unquote(n) * m
end
end
end
end
defmodule Test do
require Times
Times.times_n(3)
Times.times_n(4)
end
12 = Test.times_3(4)
20 = Test.times_4(5)
Exercise: MacrosAndCodeEvaluation-3