How do we put pattern matching on lists to use? To do this we must rely on a concept called "recursion", which basically means a function that refers to itself. The old programmer joke is that the definition of
This can be a tricky subject so don't worry if you don't get it, you don't need it for 99% of what you can do with LastCalc.
Let's say we want a function to double every number in a list, and you had to write it without using the apply ... to ... function we talked about previously.
Firstly, what would such a function return if given an empty list? Obviously if there is nothing in the list to double, then it should just return an empty list:
Here we're using a variation of the list pattern matching that we haven't seen before,  will only ever bind to an empty list. In the terminology of recursion, this is our "base case".
So great, we can now double every number in an empty list - not very useful. Here is how we define a function to double every item in a non-empty list:
double [ F ... R ] = [ F * 2 ... double R ]
What's going on here? We take a list and break it into
, the first item, and
, the remaining items. Then on the right of the = we create a new list, with first element
*2, and the rest of the elements are then doubled
using this very function
! This is the essence of recursion.
You might then ask - "If this function calls itself, won't it keep going forever"? Fortunately not, because every time it is called it is with a shorter version of the list, until eventually it is called with an empty list, and our "base case" takes care of it. Let's try it out:
double [ 1 , 2 , 3 ]
[ 2, 4, 6]
While recursion is very flexible, and can be used to do something similar to the
, and the
functions mentioned previously, it isn't very efficient. It is much better to use one of these other list manipulation functions if possible.
Sharing your LastCalc functions
So you've created some really useful functions and you'd like to share them with your friends? Not a problem. You can "import" pre-defined functions from any URL using the
command. The URL must point to one or more function definitions in plaintext, Here is a very simple example:
. To use these functions in your worksheet just type:
And then you can use them: