DEF FN

BASin

DEF FN DEFine FuNction

Statement

DEF FN enables the user to define a function that is not available as a keyword. A variety of parameters can be passed to the function in an FN statement, which calls the function and may return either a numeric or string value as a result.

How to use DEF FN

DEF FN may only be used as a statement in a program. If a numeric function is to be defined, DEF FN is followed by any single letter and then by one or more numeric variables each separated by a comma and enclosed in brackets. For example, DEF FN r(x,y). This is followed by an equals sign and then a numeric expression containing the variables, for example

1000 DEF FN r(x,y)=SQR(x↑2+y↑2)

The letter following DEF FN (r above) is a name that identifies the function. The variables may also only be single letters. Note that in both cases, the BASIC does not distinguish between capital and lower-case letters.

The expression that follows the equals sign uses the variables (x and y above) to define the function.

A DEF FN statement may be placed anywhere in the program. To call a function that it defines, a FN statement is used. This is then followed by the function name letter and a list of numeric values each separated by a comma and enclosed in brackets, for example

50 PRINT FN r(3,4)

The values in the brackets are passed to the function in the same order as the variables in the DEF FN statement. Thus, in this example, x is assigned a value of 3 and y a value of 4. FN evaluates the expression and returns the value.

DEF FN may also be followed by a letter and a pair of brackets only, for example

1000 DEF FN r()=INT (x+0.5)

The value currently assigned to the variable (x above) is passed to the function when it is called by FN. In this case, FN r() returns the value currently assigned to x rounded to the nearest integer.

DEF FN and strings

DEF FN and FN may also be used the same way to define and call a string function. In this case, the function name is a single letter followed by $ and one or more of the variables in the statement is a letter followed by $. A corresponding string expression forms the definition, for example

1000 DEF FN a$(b$,x,y)=b$(x TO y)

The string expression following the equals sign in this example is a string slicer, and x and y are the first and last characters of a section of b$. FN must be followed by the function name and, in brackets, a string value together with any other parameters that are to be passed to the function. In this case, the command

PRINT FN a$("FUNDAMENTAL",1,3)

displays FUN, and the command

PRINT FN a$("FUNDAMENTAL",5,8)

displays AMEN.

Format

  • DEF FN letter ([letter] [,letter])=num-expr
  • DEF FN letter$ ([letter$] [letter] [,letter] [,letter$])=string-expr
  • FN letter ([num-expr] [,num-expr])
  • FN letter$ ([string-expr] [,num-expr] [,string-expr])

See also

Chapter 9.