letter from ZX Computing, February 1987

[The BASIC lines below contained several printing errors in the magazine, ]
[particularly FN i(), which was an absolute mess. I've corrected the lines]
[reproduced here and checked that they all work.                          ]
[(see also the file MCCALC.TAP "Recursive")                           JimG]

Calculating

Toni Baker's machine code calculator series has been very
enlightening, even though the references given to locations in the ROM
do not apply to my T/S 2068.

I am writing because there is a slight error in the part 4 of the
series. Everything that has been said about the machine code
calculator, or other ROM routines, is accurate for the 2068 as well -
after adjusting for the different locations of the routines. However,
the author on page 64 (October) suggests that it is not possible to
define the factorial function with a BASIC DEF FN statement. Well, the
Spectrum or the 2068 is a machine of many surprises, so perhaps we
should not be too shocked to discover that indeed we can use DEF FN to
define the factorial function using only BASIC.

The technique used for this is called a recursive function definition.

The following statement will define a function whose value - if the
argument is a positive integer - is the factorial of N:

  10 DEF FN f(n)=n*VAL (("FN f(n-1)-1" AND n>1)+"+1") OR n<>1

Similarly it is also possible to define the function F$ that he
mentions in only BASIC or a function which does what INSTR does on
other computers. These would look as follows:

  20 DEF FN f$(x$,x)=(x$ AND x>=.5)+VAL$ (("FN f$(x$,x-1)" AND x>=1.5)+"+""""")

  30 DEF FN i(s,a$,b$)=s*(a$(s TO s+LEN b$-1)=b$)+VAL (("FN i(s+1,a$,b$)" AND s+
LEN b$<=LEN a$ AND a$(s TO s+LEN b$-1)<>b$)+"+0")

For F$ and F I suggest you see part 4 of the machine code calculator
article. The function FN I(S,A$,B$) has as its value the location of
the first occurrence of B$ in A$ after the Sth character. For example,
FN I(3,"ZX Computing","put") is 7, since the string "put" can be found
starting with the 7th character in "ZX Computing". If I had set the
number at 8 instead of 3, the answer would have been 0 since "put"
does not occur starting with or after the eighth character.

This is not to say that defining such functions in BASIC is the way to
go - the function definitions above are pretty slow if some of the
numbers or strings are large. This is because finding the factorial of
10 using the above function for it actually has to evaluate the
function 10 times. Also, one must be careful with recursive functions
to make sure that the function will reach an end eventually. Finally,
because of the way the Spectrum and 2068 handle recursive functions,
the function call must be the last thing evaluated.

Keep up the good work with your fine magazine.

Steven V Gunhouse, Winsor, Ontario, Canada.
