 # DEF FN for Fun and Profit

In a comment to my recent article about VARPTR, Rogelio Perea chimed in…

Still learning something new about the CoCo even after all the years, excellent article!

Would there ever be one about DEFFN? :-)

–  Rogelio Perea II, 7/19/2022

Challenge accepted.

## DEF FN: Definitely Fun?

There are many features of Microsoft Color BASIC that went right over my head when I was learning to program as a junior high school kid. DEF FN was certainly one of them.

My first CoCo came with Extended Color BASIC, and that was required to use DEF FN. But what is is? According to Getting Started with Extended Color BASIC:

Extended Color BASIC has one numeric function, DEF FN, that is unlike any others we’ve talked about so far. DEF FN lets you create your own mathematical function. You can use your new function the same as any of the available functions (SIN, COS, TAN, and so on). Once you’ve used DEF FN to define a function, you may put it to work in your program by attaching the prefix FN to the name you assign to the new function. Here is the syntax for DEF FN:

DEF FN name (variable list) – formula

name is the name you assign to the function you create.
variable list contains one “dummy variable” for each variable to be used by the function.
formula defines the operation in terms of the variables given in the variable list

Note: Variable names that appear in formula serve only to define the formula; they do not affect program variables that have the same name. You may have only one argument in a formula call; therefore, DEF FN must contain only one variable.

You may use DEF FN only in a program, not in the immediate mode.

– Getting Started with Color BASIC, page 177.

I think my work here is done.

Until next time…

Okay, maybe not.

## DEF FN: Define Function

There are commands in BASIC, such as PRINT and GOTO, and then there are functions that return values, such as SIN, ABS and INT.

```PRINT SIN(42)
-.916521549

X=-42
PRINT ABS(X)
42

X=4.2
PRINT INT(X)
4```

DEF FN allows you to create your own function that returns a value.

## A simple example

We start with a simple example. What if you wanted a function that added 42 to any value you passed in? I will call this function “UA” (for “Ultimate Answer”) and define it as follows:

```10 DEF FNUA(N)=N+42
20 PRINT FNUA(10)```

If I run that, it will print 52. The new “function” FNUA(x) returns whatever you pass in with 42 added to it. Tada!

Function names seem to follow the same rules as variable names so you can have one or two letters (A to Z, AA to ZZ) or a letter and a number (A0 to Z9).

In the parens is a parameter that also follows the same rules of a variable. The parameter is just a placeholder so you have something to use in your new formula on the right of the equal sign. If you did DEF FNA(X) then after the equal you’d have whatever you want to happen to X. When the user calls it with FNA(123) then 123 goes to where the X was in the formula after the equals… Neat.

It’s kind of like a C function with only one parameter, now that I think about it/

```// fnua(n) - return n plus 42
int fnua(float n)
{
return n+42;
}

int main()
{
float x = fnua(10);

printf ("x = %f\n", x);

return EXIT_SUCCESS;
}```

You can have DEF FNA(X) or DEF FNZZ(AB) or any combination.

## What can you use it for?

The manual gives an example of doing math with a long floating point value so you don’t have to have that value in your code everywhere you want to use it.

```7 DEF FNR(X)=X/57.28577951
6 AA=FNR(AA): AB=FNR(AB): AC=FNR(AC)```

At least I’m not the only one with code snippets that don’t really do anything.

Of course, for something like this you could have placed that number in a variable which would be faster than parsing a long number (in most cases). Still, if the formula itself is big, it could save typing, I guess.

## Benchmarks, anyone?

I was curious if it would be any faster for other types of maths…

Suppose I want to use PRINT@ to put a character on the text screen, but want to use PEEK to see if it “hits” another character on the text screen. I would use the PRINT@ positions of 0-511, but I’d want to PEEK the screen memory locations of 1024-1535.

```10 CLS:P=0
20 FOR I=1 TO 20:PRINT@RND(511)-1,"X";:NEXT
30 PRINT @P,"*";
40 A\$=INKEY\$:IF A\$="" THEN 40
50 IF A\$="W" THEN NP=P-32:GOTO 90
60 IF A\$="A" THEN NP=P-1:GOTO 90
70 IF A\$="S" THEN NP=P+32:GOTO 90
80 IF A\$="D" THEN NP=P+1
90 IF NP<0 THEN 40
100 IF NP>510 THEN 40
110 IF PEEK(NP+1024)<>96 THEN 40
120 PRINT @P," ";
130 P=NP
140 GOTO 30
```

Above is a program that will clear the screen and put X characters in random positions. The player is an asterisk in the top left of the screen. Using the keys W (up), A (left), S (down) and D (right) will move the asterisk around the screen. Checks ensure you cannot go off the top or bottom of the screen, or run in to an X.

Line 110 does the conversion from PRINT@ position to PEEK position. Maybe we can do this:

```0 ' defusr2.bas
10 CLS:P=0
15 DEF FNP(X)=X+1024
20 FOR I=1 TO 20:PRINT@RND(511)-1,"X";:NEXT
30 PRINT @P,"*";
40 A\$=INKEY\$:IF A\$="" THEN 40
50 IF A\$="W" THEN NP=P-32:GOTO 90
60 IF A\$="A" THEN NP=P-1:GOTO 90
70 IF A\$="S" THEN NP=P+32:GOTO 90
80 IF A\$="D" THEN NP=P+1
90 IF NP<0 THEN 40
100 IF NP>510 THEN 40
110 IF PEEK(FNP(NP))<>96 THEN 40
120 PRINT @P," ";
130 P=NP
140 GOTO 30
```

The behavior is the same, and now I get the benefit of it not having to parse “NP+1024” each time. Parsing decimal values is slow. On Extended BASIC I could have replaced 1024 with hex &H400 and that would have been faster. For more speed, I could have used a variable and had “NP+S” or whatever.

But is it faster?

```0 ' defbench1.bas
5 P=0
10 TIMER=0
20 FOR A=1 TO 1000
30 Z=P+1024
40 NEXT
50 PRINT TIMER```

Doing “P+1024” 1000 times prints 481.

```0 ' defbench2.bas
5 P=0
6 DEF FNP(X)=X+1024
10 TIMER=0
20 FOR A=1 TO 1000
30 Z=FNA(P)
40 NEXT
50 PRINT TIMER
```

That version prints 603. Not faster. The overhead of FN seems to be more than just doing it directly. In a way, this makes sense because in-lining code in assembly or C is faster than calling it as a subroutine/function.

But let’s try more… We could also include other things in the function, like the PEEK itself.

```0 ' defbench3.bas
5 P=0
6 DEF FNP(X)=PEEK(X+1024)
10 TIMER=0
20 FOR A=1 TO 1000
30 Z=FNP(P)
40 NEXT
50 PRINT TIMER
```

That one prints 690, and if you had just done “30 Z=PEEK(P+1024)” it would have been 572.

Cool, but definitely slower. I believe this is because it’s still storing that formula in a buffer somewhere and executing it as if you’d just typed it in. Indeed, if you change the formula to use hex:

```0 ' defbench3.bas
5 P=0
6 DEF FNP(X)=PEEK(X+&H400)
10 TIMER=0
20 FOR A=1 TO 1000
30 Z=FNP(P)
40 NEXT
50 PRINT TIMER```

…it prints 480, which means it’s parsing that formula each time instead of converting it to a number when you define it.

Pity. It would have been really cool if this had been a way to bypass the detokenizer stuff in BASIC and speed up routines like that.

## FN Conclusion

DEF FN is slower. I don’t see any example where it speeds anything up. With that said, I expect I’d use DEF FN if…

• I had a custom function I used in multiple places, and wanted to maintain it in just one spot. This would be more efficient, perhaps, than making it a GOSUB subroutine.
• I needed to save some bytes of BASIC memory.
• I wanted to write an example that fix things on small lines on the screen, just for appearances.

For anything else, I think I’d just put it in and make the program a bit faster.

Where else might one use this?

## More examples

Sebastian Tepper commented to another post with a more useful example for DEF FN. There are many times when we use two PEEKs to get a 16-bit value from two bytes in memory:

`V=PEEK(25)*256+PEEK(27)`

Sebastian mentioned using DEF FN for this:

```DEF FNP(AD)=PEEK(AD)*256+PEEK(AD+1)

V=FNP(25)```

That’s very cool, and something I could see myself using. I wish I had thought of that when I was doing all my “Color BASIC memory location” articles, since I typed the double PEEK lines over and over and over…

But that’s not all…

The defined function can also use other variables. You can only pass one in, but any variable that is declared at the time the FN is used may be used. You could do this:

```10 DEF FNA(X)=X*Y
20 Y=10
30 PRINT FNA(Y)
RUN
50```

Above, you pass in a value for “X” and it returns the value multiplied by whatever Y is at that moment. You could create more complex formulas that way, but it kind of defeats the purpose.

Speaking of defeating the purpose, here are more silly examples. Using it to replicate PEEK:

```10 DEF FNP(X)=PEEK(X)
20 PRINT FNP(1024)```

How about returning if something is true or not? Like, is a memory location outside screen memory?

…but that sure looks like it would be really slow. Still neat, though. You could do:

`IF FNL(L) THEN PRINT"NOT IN SCREEN MEMORY"`

It does make the code look neater — especially if something is being checked multiple times (such as checking four ghost in Pac-Man or whatever).

Until next time…

## 9 thoughts on “DEF FN for Fun and Profit”

1. William Astle

It’s unfortunate that DEF FN() doesn’t allow defining functions with multiple parameters. The documentation implies that it is possible with references to parameter lists and at least one part actually lists the syntax accepting multiple parameter variables, so it seems it was originally supposed to accept multiple parameters. Alas, the ROM doesn’t implement multiple parameters.

There’s a technical reason for it, but it is unfortunate. That technical reason could have been worked around, though. I can think of a couple of ways they could have done so.

1. Johann Klasek

Maybe this was someone’s idea to do so (at least the author of the manual ;) ). I think DECB simply inherited the core behavior from MS BASIC. There was a lot of other things to improve than making DEF/FN better that way.

2. Rogelio Perea II

Adapted for Color BASIC from “Basic Faster and Better” by Lewis Rosenfelder, page 74:

10 DEF FNRW(A)=FIX((FIX(A10)+SGN(A)5/10)
20 DEF FNRD(A)=FIX((FIX(A1000)+SGN(A)5)/10)/100
30 CLS:INPUT”VALUE TO ROUND”;V
40 PRINT:PRINT
50 PRINT”ROUND TO NEAREST WHOLE”;FN RW(V)
60 PRINT”ROUND TO NEAREST CENT”;FN RD(V)
70 PRINT:END

Take it for a spin on numbers with a few decimals to boot.

Thanks for the follow up on DEF FN, there has to be more that can be done with that rarely used facility in Color BASIC – as William commented before me, it’d be better if the definition could support multiple variables on its definition. Microsoft cut the wrong corner on this one.

3. Johann Klasek

”Cool, but definitely slower. I believe this is because it’s still storing that formula in a buffer somewhere and executing it as if you’d just typed it in.”

It’s the way around: Find the function (it is stored in the variable table and has to be searched like other variables with the linear drawback), search and save the parameter variable on stack, setup the parameter variable, followed by switching the running context temporarily to the function code, clean up the stack (restore the parameter variable) and back to the calling point.
Lot of run-time overhead occurs for each call. This disadvantage might only outweighed if you truly save code space and gain some sort of security against typos if repeated code is factored out by function declaration.

1. Allen Huffman Post author

Is it jumping to the code just after DEF FN, I wonder? I guess it cannot, since it has to substitute. Maybe if you say DEF FNX(I) it makes a temporary I, then runs the code on that line, then restores? I need to look. Now I’m quite curious at how it is implemented.

1. William Astle

It does, indeed, jump to the code in the DEF FN statement. There is no substitution done in a buffer. Instead, it saves the value of whatever is in the named dummy variable, puts the parameter there, then restores the original value of the dummy variable afterward.

Astute readers may notice that gives a sort of dynamic scoping of parameter values if an FN call is made inside another FN call. Say you define FNA(X) and FNB(Y). If FNA calls FNB, then from within FNB, the value of X will be whatever was passed into FNA.

1. Allen Huffman Post author

That’s interesting. I did not even think of having an FNx call another.

1. Johann Klasek

Indeed, quite rare in use, but possible … Loops through a chain of different FNs has to be avoided (or recursions), because – at least to my knowledge – you don’t have any conditional element to prevent a FN-call (defining some exit condition) and to break up the calling chain …

2. Johann Klasek

Just for comparison look at CBM’s BASIC implementation which has the same roots. See https://www.c64-wiki.com/wiki/FN which shows the stack-frame used (which might vary on 6809 platform in regard of the calling sequence of the interpreter’s subroutines to perfom the FN). ;)

This site uses Akismet to reduce spam. Learn how your comment data is processed.