Sometimes, when doing encryption it is useful to shuffle sets of characters, for example when creating substitution keys.
In the past I have just written simple scripts in FileMaker to do this because, although I have used and adapted recursive custom functions several times, I have never really understood the difference between a normal recursive function and a tail recursive function.
This is important because the normal form is limited to 10,000 cycles in FileMaker but the tail form can run to 50,000 cycles.
The other day I had to create a shuffle routine within a database definition hence, as I couldn't script it, I had to work out how to create a suitable recursive function.
A quick search found an erudite explanation by Ray Cologon from 2006 which explained the difference...
Here is the key quote:
"Tail recursion has nothing to do with whether you 'loop' backwards from the end or forward from the beginning. What matters is how values accumulate and are passed down through successive function calls (and in particular, whether the function must feed values via a temporary memory 'stack' in the course of its operation). In the simplest terms, recursive functions that are constructed so that they don't depend on the stack are tail recursive."
In other words, it is tail recursive if you pass all the results of the expression on to the next iteration as parameters without creating local variables.
With that understood it was fairly simple to construct my shuffle function so that it output the shuffled string and a control value, so the control value reduced by 1 on each call and the result of the expression no longer called itself when the control had reduced to zero.
Here it is
FileMaker Custom Function - Tail Recursive
By Nick Lightbody September 7th, 2015
Purpose:To shuffle a string
xShuffle ( string; control )
Input: string to be shuffled
Input: number of times xShuffle should call itself i.e. to control the extent of the shuffle