Apple II

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...
 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)
The DATA statements contain the bytes for the USR machine-language routine:
300:
:A5 9D
:F0 3
:20 95 D9
:60
 | 
 | 
 | 
 | 
 | 
 
        LDA FAC	  ; CONDITION TRUE OR FALSE?
        BEQ done  ; BRANCH IF FALSE
        JSR $D995 ; MOVE TO NEXT STATEMENT
done    RTS

This method is very limited for recursion as Applesoft function calls are limited to four calls deep.

OUT OF MEMORY ERROR

Posted on October 6, 2013 by mmphosis

http://macgui.com/usenet/?group=2&id=23626