User Tools

Site Tools


ch2_1_defun

This is an old revision of the document!


DEFUN

DEFUN form defines a named ordinary function object in global scope. It needs at least one symbol argument, which is not evaluated and will be the name of the function. Defun with no other arguments creates a function that evaluates to NIL. For any practical use, we need to supply more arguments. Second argument must then be a list of parameters (symbols) of the function, the symbols are not evaluated and will be used for local binding of parameters once the defined function is called. In fact, no parts of the DEFUN expression are evaluated during the definition. Third argument is optional description string. If the third argument is not string, it is considered first form of the function body. Any other parameters are to DEFUN are stored as the function body.

>(defun adder (a b)  ; function named ADDER, arguments A, B
   “replaces plus”   ; optional description string 
   (+ a b))          ; body expression
ADDER                ; DEFUN returns the symbol naming the new function   

In this example we have created function adder. Its body contains single arithmetic function. The newly defined function can be called as any other function. Result of the function ADDER will be result of the + function.

>(adder 2 4)
6

If function body contains more expressions, all are evaluated sequentially (once the function is called), but only the output of the last one is returned from the function (this behavior is due to implicit PROGN).

In LabLisp it is not (yet) possible for user to define function with variable number of parameters. But some of the built-in functions support that (e.g. + or LIST), and it is planned feature for user defined functions too.

Functions have lexical closure. In simple terms, it means that, when called, the function body expressions are evaluated in the environment, where the function was defined.

>(let ((a 1))                        ; A is local variable
   (defun add-a (b) (+ a b))         ; adds the argument B to the stored A
   (defun set-new-a (x) (setq a x))) ; changes the stored A  
SET-NEW-A                            ; LET form returns the result

The two functions share the lexical environment LET, that means they both can access the same A symbol.

>(add-a 3)            ; calling the new function
4                    ; it adds 3 to the stored A
 
>(set-new-a 5)       ; now the stored value is changed
5
 
>(add-a 3)
8                    ; new value A is used (5+3)
ch2_1_defun.1620281573.txt.gz · Last modified: 2021/05/06 00:12 by admin

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki