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:
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 ...
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy