In traditional Lisp (Common Lisp), when evaluating an S-expression list, the first element in the “functor” position must be a function or valid operator. newLisp relaxes this requirement and allows the first element to be a context symbol type, a list, an array, or an integer. For today’s discussion, let us ignore the context symbol, but look at examples of the other types.
Let us start with the “List” type. Take a look at the following snippet:
First, we assign to “list1” variable a list of symbols. Then we use the same variable in the “functor” position, followed by an integer argument. Even though “list1” is not a “function”, newLisp evaluates this S-expression, treating it as an “indexing” operation, returning the third element of the list (indices start from zero). An error is signalled when we index beyond the list size.
We could have also used the built-in function “nth” to access the list element, but newLisp supports the above shortcut.
Here is another example involving a nested list:
As you can see, it is possible to access an element of the nested list in two ways. The last example shows how we can directly use a list literal in the first argument position.
What about “arrays”? Let us create two one-dimensional arrays:
The second array above has a nested item that has 3 elements in it.
We can access the array elements this way:
What about multi-dimensional arrays? The logic is quite similar.
The above creates and uses a 2 by 3 array.
It is possible to use a -ve index:
The index “-1” represents the last element of the array.
Since Strings are implicitly arrays, we can use the same indexing mechanism:
A natural extension of “implicit indexing” that we have seen so far is “implicit slicing”. Slicing comes into picture when we use an integer in the “functor” position.
Check this out:
The first expression returns a sublist starting from the second element of the given list. Another integer argument, if provided, specifies the number elements to extract from the starting position.
The following shows slicing applied on arrays and strings:
Of course, we can also use integer variables instead of literals for slicing, as shown below:
According to the official documentation, implicit indexing is optional (we can always use “nth”, etc.) and when used, it improves performance.
Have a great week ahead!
Recent Comments