newLisp is a general-purpose scripting language with a Lisp-like syntax. That is one of the reasons I wanted to take a closer look at the language. It has a compact footprint, small resource requirements, and can easily be embedded. It is available on multiple platforms, and on my Windows machine, the installation has just two files: newlisp.exe and newlisp.dll
newLisp boasts of many interesting features, and I hope to explore them gradually. In today’s article, let me touch upon two of them.
Random Expression Evaluation
The function “amb” takes one or more arguments, selects one of the arguments at random, evaluates it, and returns that as its result/value.
Nothing fancy here, since it is quite easy to implement this behavior using “rand” function. However, given that it is available by default, we have a ready-made starting point for implementing non-deterministic functionality in our code. The important thing to remember is that only one of the arguments is evaluated. Since function arguments could be arbitrary expressions, we do not want to evaluate them unnecessarily even though only one of them is “returned” as result. The “amb” function handles this correctly. See the following example:
The first value printed is from argument evaluation and the second value is the final result. You can see that both are the same.
If you are curious, here is one way to implement the functionality provided by “amb”:
I am using a “macro” to suppress normal argument evaluation. Quite straightforward.
Functions with State
newLisp supports the notion of “Namespace” or “Context”. Based on this idea, it is possible to use a simple “trick” to associate “state” with functions.
Let us write a function that returns successive even numbers starting from zero.
Here, NextEven:NextEven is called a “default function” since it has the same name as its namespace, that is, “NextEven”. NextEven:curvalue is a “static” variable within the same namespace. The NextEven function uses this “lexically isolated” variable to save its state across invocations.
Here is what happens when you execute the NextEven function:
Thus, everytime the function is called, it correctly returns the “next” even number.
What if we want to start from Zero again? No worries! We can write another “helper” function in the same “context” to reset the static variable. Here is how:
Here is an execution sequence showing the “Reset” logic:
Elegant, isn’t it? Note that we cannot just use the syntax (Reset) unless the current context is NextEven (more about contexts in a future article).
These are the two features I wanted to discuss today. There are many more appealing features in “newLisp” and I will try to cover some of them in future articles.
The version of newLisp I used is 10.7.5 (64 bit) running on Windows 10.
Have a nice weekend!
Recent Comments