-
Notifications
You must be signed in to change notification settings - Fork 17
5.19 Function Arguments
LispE provides many mechanisms to define function arguments and how they are called.
When defining the parameters of a function, via defun or lambda, it is possible to declare certain parameters as optional.
To do this, simply declare the parameters as a list. If these lists contain two items, then the second one is considered as the default value.
(defun test (i (j -2)) (+ i j))
(print test(10 20))
30
(print test(10))
8LispE provides a specific notation for functions that can take a variable number of arguments. This notation is also a list where the first element is the empty list and the second is a parameter in which supernumerary arguments are stored as in a list. This description should be the last element of your parameter definition.
; All arguments after 'x' are stored in 'l'
(defun variadic(x (() l)) ...); this function takes at least two arguments
(defun test(x y (() l))
(println x y l)
)
(test 10 20 30 45 90 900 10) ; displays: 10 20 (30 45 90 900 10)
Important: These list items should always be declared at the end of the parameter list, not in the middle.
It is also possible to call a function and to instantiate the arguments by their name in the function definition. We use then the ? operator, which takes as input the argument name and its value. Note, that in this case the order, in which elements are called is not longer important.
(defun teste(a b (c 10) (d 20)) (println a b c d))
; You can then call teste with its arguments named:
(teste 10 20 (? c 3) (? d 4))
; In which order you want:
(teste 10 20 (? d 3) (? c 4))
; if an argument is optional, then you can skip it...
(teste 10 20 (? d 4)) ; here c is 10