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:
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:
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:
Now, it is time to actually put our macro to use. Here is a 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!
Recent Comments