Applesoft USR(condition) and recursive functions
DEF FN var(arg)=expr defines a mathematical function of at most one line for later use as 'FN var(arg)'. 'arg' is a placeholder variable name; it can be used in expr to pass variables in. However, 'arg' can be used elsewhere in the program without worrying about side effects from function definition or calls. Functions can call other functions, but may not be recursive. Functions may be redefined if desired with another DEF FN block.
Using the USR function and DEF FN, we are able to create recursive functions in Applesoft. A small USR machine-language routine checks if the floating point accumulator is not zero, and if so the rest of the statement is ignored. This makes USR(condition) act like an "if" function in an expression. Here is an example of a recursive factorial function using USR...
The DATA statements contain the bytes for the USR machine-language routine:
10 A = 768:L = 7
20 DATA 165,157,240,3
30 DATA 32,149,217,96
40 FOR I = A TO A + L
50 READ B: POKE I,B: NEXT
60 H = 256: POKE 12,A / H
70 POKE 11,A - PEEK (12) * H
80 DEF FN FA(N) = USR (N < 2) + N * FN FA(N - 1)
90 PRINT FN FA(4)
:20 95 D9
LDA FAC ; CONDITION TRUE OR FALSE?
BEQ done ; BRANCH IF FALSE
JSR $D995 ; MOVE TO NEXT STATEMENT
This method is very limited for recursion as Applesoft function calls are limited to four calls deep.