exercises and notes from "Gentle introduction"
This commit is contained in:
59
optional-arguments.lisp
Normal file
59
optional-arguments.lisp
Normal file
@@ -0,0 +1,59 @@
|
||||
;;; &optional (with and without default value)
|
||||
;;; &rest
|
||||
;;; &key (with or without default value)
|
||||
;;; &aux - similar to LET* - additional variables, that can be calculated from other inputs, for example &rest
|
||||
;;;
|
||||
;; cool
|
||||
|
||||
;; default argument
|
||||
(defun lala-1 (x &optional y)
|
||||
(format t "~&x value is ~S" x)
|
||||
(format t "~&y value is ~S" y)
|
||||
(list x y))
|
||||
|
||||
(lala-1 2 5)
|
||||
(lala-1 7)
|
||||
|
||||
(defun lala-2 (x &optional (y 2))
|
||||
(format t "~&x value is ~S" x)
|
||||
(format t "~&y value is ~S" y)
|
||||
(list x y))
|
||||
|
||||
(lala-2 1 5)
|
||||
(lala-2 7)
|
||||
|
||||
;; rest arguments - accessed as list, unlimited number on call
|
||||
(defun lala-3 (x y &rest args)
|
||||
(append (list x y) args))
|
||||
|
||||
(lala-3 7 5 1 2 34 5 6)
|
||||
|
||||
;;; keyword arguments
|
||||
(defun make-sundae (name &key (ice-cream `vanilla)
|
||||
(syrup `chocolate)
|
||||
nuts
|
||||
cherries
|
||||
whipped-cream)
|
||||
(list 'sundae
|
||||
(list 'for name)
|
||||
(list ice-cream 'with syrup 'sypup)
|
||||
(list 'toppings '=
|
||||
(remove nil
|
||||
(list (and nuts 'nuts)
|
||||
(and cherries 'cherries)
|
||||
(and whipped-cream 'whipped-cream))))))
|
||||
|
||||
(make-sundae 'yo)
|
||||
(make-sundae 'yo
|
||||
:syrup 'maple
|
||||
:whipped-cream t)
|
||||
|
||||
;;; auxillary variables
|
||||
;; &aux - additional local variables?
|
||||
;; "a matter of taste, whether to use LET* around body or &aux attributes"
|
||||
|
||||
(defun my-average (&rest args
|
||||
&aux (len (length args)))
|
||||
(/ (reduce #'+ args) len))
|
||||
|
||||
(my-average 1 2 3 4 5 6)
|
||||
Reference in New Issue
Block a user