You can program a script to call other scripts or to call itself. Nesting scripts makes it easier to take a block of functionality and use it multiple times or to solve problems that can be described recursively.
The following example script shows how to use recursion (a script calling itself) to calculate factorials:
If (Number_Equal(ArgumentValue,1))
Comment: The factorial of 1 is 1
Return
End_If
If (Number_Not_Equal(ArgumentValue,0))
Comment: The factorial of X is X multiplied by the factorial of X – 1
Temp=ArgumentValue
ArgumentValue=Number_Minus(Temp,1)
Call: Factorial
ArgumentValue <-> ArgumentValue
ArgumentValue = Number_Multiply(Temp,ArgumentValue)
Return
End_If
ArgumentValue = Ask_Number("Enter a number:", "Factorial Calculator",1,12,0)
Call: Factorial
ArgumentValue <-> ArgumentValue
Ask_OK(String_Combine("The factorial is", Number_To_String_Decimal(ArgumentValue)), "Result")
Return
This script uses two integer variables, ArgumentValue and Temp.
When a script calls another script, the calling script can assign values to the called script variables. The factorial example script knows it is being called recursively because the ArgumentValue variable is not 0. If ArgumentValue is 0, the script will ask for the number to calculate the factorial with. Each time the script is called, the ArgumentValue variable of the calling script is assigned the final value in the called script’s ArgumentValue variable. This keeps the results of the called script’s actions from being lost. (If the value were not returned, then there would be a "<--" instead of a "<->" in the Call action’s argument list.) When you add the action for calling a script, you need to specify which variables in the called script will be assigned a value, and what that initial value will be.
If you wanted to be more efficient, you could create a While loop that performs the multiplications to calculate the factorial. You could also return the proper response for each factorial, since numbers higher than 12 exceed the maximum number value. However, there are some problems that are easiest to solve using recursion. The example above may give you an idea how you could use it.
Was this article useful?
The topic was:
Inaccurate
Incomplete
Not what I expected
Other