...

/

Custom Language Constructs

Custom Language Constructs

Learn to create custom macros for if-condition and while-loop in Elixir.

We’ve learned that macros allow us to effectively create our own keywords in the language, but they also allow Elixir to be flexible against future requirements.

For example, instead of waiting for the language to add a parallel for comprehension, we could extend the built-in for macro with a new para macro that spawns processes to run the comprehensions in parallel.

It could look something like this:

Press + to interact
para(for i <- 1..10 do: i * 10)

If implemented, para would transform the for AST into code that runs the comprehension in parallel. The original code would gain just one natural para invocation while executing the built-in comprehension in an entirely new way.

José, the creator of Elixir, gives us a solid language foundation that we can craft to meet our needs.

Re-creating the if macro

Consider the if macro from our unless example in the lesson Macros: The Building Blocks of Chapter 2. The if macro might appear special, but we know it’s a macro like any other.

Let’s recreate Elixir’s if macro to learn how easy it is to implement features using the building blocks of the language.

Consider the following example:

defmodule ControlFlow do

  defmacro my_if(expr, do: if_block), do: if(expr, do: if_block, else: nil)
  defmacro my_if(expr, do: if_block, else: else_block) do
    quote do
      case unquote(expr) do
        result when result in [false, nil] -> unquote(else_block)
        _ -> unquote(if_block)
      end
    end
  end
end
A `ControlFlow` module with `my_if` macro.

Note: Run the project and ...