Here is an example given by google of a Named function using recursion
=IF(ISERROR(FIND(" ", str)), str, REVERSE_WORDS(RIGHT(str, LEN(str)-FIND(" ", str)))&" "&LEFT(str, FIND(" ",str)-1))
This function will take "1 2 3 4" and the final output will be "4 3 2 1" but I am trying to understand exactly why this is occurring specifically by taking it step by step and this is what I have so far:
Imaginary Debugging
Step 1
iserror false
Step 2
REVERSE_WORDS( "2 3 4" )
Step 3
iserror false
Step 4
REVERSE_WORDS( "3 4" )
Step 5
iserror false
Step 6
REVERSE_WORDS( "4" )
Step 7?
iserror true so return 4?
Step 8?
???
I don't understand exactly how the final output becomes "4 3 2 1" can someone please write out the remaining steps or correct them for me to visualize since I can't debug/evaluate functions in google sheets. I understand &" "&LEFT(str, FIND(" ",str)-1))
will output 1 then 2 then 3 and then not trigger the forth time because of the iserror but it seems like the output should be "4 1 2 3" or just "4 1" or "4 3".
Recursion is a programming strategy, where a function calls itself. If a function is made to call itself, it can call itself indefinitely. For recursion to return a valid value, the exit strategy should be inside the function itself.
Here, the exit strategy is provided
ISERROR
. During each recursion, the function checks, ifFIND()
throws a error, if it throws a error, the function returns thestr
ing, else it keeps calling itself. Whenever it calls itself, it leaves a value.REVERSE_WORDS()&" "&LEFT(str, FIND(" ",str)-1))
Here, it leaves
LEFT(str, number of characters)
on each call. The number of characters is determined by finding the first space in the string. In the case ofNote that the first return is the real return or the return we receive from calling
REVERSE_WORDS( "1 2 3 4" )
. That return isThe
REVERSE_WORDS( "2 3 4" )
call in that first return returns:Combined, the first return can be written as,
If we keep substituting(recursing), we get,
which is
1 2 3 4
?Because of the order of operation. If we change
to
We'll get
1 2 3 4