Elixir: Wrapping Lisp Calls in a Macro

Written by on August 1, 2020 in Elixir, LISP, Programming with 0 Comments

In the last article, I showed how to make calls to Lisp functions from Elixir. We followed this pattern:

1) Initialize the Lisp environment by calling Lisp.init

2) Call Lisp functions as needed

3) Free the Lisp environment by calling Lisp.quit

Using the powerful macro programming capabilities of Elixir, we can write a simple macro to wrap calls to Lisp functions, by adding Lisp.init and Lisp.quit automatically. This way, we do not have to worry about “forgetting” to handle initialization and termination. Such an approach is quite common when we program in Lisp itself.

I have made a minor change in the Lisp NIF layer, corresponding to the “quit” function, to ensure that “init” and “quit” can be called multiple times as a pair. Here is the modified version:

Updated Quit Function

Updated Quit Function

Elixir macros are a major topic and we are not getting into the details here. There are several nice tutorials available on the internet. For example, see this and this.

Here is our macro:

Our Macro

Our Macro

Macros can be difficult to understand and debug. So it helps if we have a utility function that shows how a macro call is actually expanded by Elixir. Writing such a function (a macro again!) is straightforward. I took the following code snippet from this article:

Understanding Macro Expansion

Understanding Macro Expansion

Now, it is time to actually put our macro to use. Here is a sample session:

Sample Session

Sample Session

Since we are calling a macro, we have to “require Lisp” first. Additionally, for convenience, I am importing the same package. This allows us to use the functions in the package without explicitly using the package prefix.

You can also see how “mex” dumps the expanded macro call. Lisp.init and Lisp.quit are automatically inserted at the beginning and end respectively by our “with_lisp” macro.

The updated NIF “C” source and the Elixir code are available here.

Have a nice weekend!

Tags: , , ,


If you enjoyed this article, subscribe now to receive more just like it.

Subscribe via RSS Feed

Leave a Reply

Your email address will not be published. Required fields are marked *