ch2_1_defun
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
ch2_1_defun [2022/02/23 06:54] – admin | ch2_1_defun [2022/03/31 04:57] (current) – admin | ||
---|---|---|---|
Line 19: | Line 19: | ||
If function body contains more expressions, | If function body contains more expressions, | ||
- | 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. '' | + | === Optional parameters === |
+ | |||
+ | Since LabLISP | ||
+ | |||
+ | <code lisp> | ||
+ | (defun foo (a b & | ||
+ | </ | ||
+ | |||
+ | Such definition will create function with minimum 2 and maximum 4 parameters. If the the optional parameters are not supplied, when calling | ||
+ | |||
+ | <code lisp> | ||
+ | >(defun adder (a b & | ||
+ | (+ a b c)) ; C defaults to 0, so the + will work | ||
+ | ADDER | ||
+ | </ | ||
+ | |||
+ | Eventually, the initializer can contain additional parameter, which will indicate, whether the user actually supplied the optional argument. | ||
+ | |||
+ | <code lisp> | ||
+ | >(defun adder (a b & | ||
+ | (if d (print "c supplied" | ||
+ | (+ a b c)) | ||
+ | ADDER | ||
+ | >(adder 1 2) | ||
+ | "c not supplied" | ||
+ | 3 | ||
+ | >(adder 1 2 0) | ||
+ | "c supplied" | ||
+ | 3 | ||
+ | </ | ||
+ | |||
+ | Functions can as well be defined | ||
+ | |||
+ | <code lisp> | ||
+ | >(defun adder (&rest a) ; parameter A represent any number of arguments | ||
+ | | ||
+ | ADDER | ||
+ | >(adder 1 2 3 4 5) | ||
+ | 15 | ||
+ | </ | ||
+ | |||
+ | The function will receive any number of arguments as list A. | ||
+ | |||
+ | The mandatory, optional and rest paramters can be combined. Order of the keywords ''& | ||
+ | |||
+ | === Lexical closure === | ||
Functions have lexical closure. In simple terms, it means that when called, the function body expressions are evaluated in the environment, | Functions have lexical closure. In simple terms, it means that when called, the function body expressions are evaluated in the environment, |
ch2_1_defun.1645624477.txt.gz · Last modified: 2022/02/23 06:54 by admin