Dana Vrajitoru
C311 Programming Languages

Type Checking, Optional Parameters, Function Invocation

Type-Checking Predicates

Example

(defun plus-maybe (n m)
  (let ((r 0))
    (if (numberp n) (setq r (+ r n)))
    (if (numberp m) (setq r (+ r m)))
    r))
(plus-maybe 3 8) ; 11
(plus-maybe 3 'a) ; 3
(plus-maybe '(2 3 9) 4) ; 4
(plus-maybe 'a 'b) ; 0

Optional Parameters

Example
(defun fun (a b c &optional d e &rest f) ...)

(defun my-make-list (length &optional init &rest endlist)
  "Creates a list by making length copies of init and appending endlist to it 
   afterwards. If the init is missing the list is filled with 0s."
  (let ((L nil))
    (setq L (if init (make-list length init)
              (make-list length 0)))
    (append L endlist)))

(my-make-list 4 2 7 8) ; (2 2 2 2 7 8)
(my-make-list 5) ; (0 0 0 0 0)
(my-make-list 3 0 1 1) ; (0 0 0 1 1)

(defun my-print (&rest L)
  "Prints any number of arguments with princ and returns true."
  (mapc 'princ L) t) ; my-print
(my-print "hello world " 1 " " 2  " n= " 4 "\n")
; hello world 1 2 n= 4
; t
(defun plus (&rest L)
  (apply '+ L)) ; plus
(plus 1 2 3) ; 6

Explicit Function Invocation

(funcall function arguments)
(apply function (list-of-arguments))

(setq f (lambda (x y) (* x y)))
; (lambda (x y) (* x y))
(funcall f 2 5) ; 10
(apply f '(2 5)) ; 10
(apply '+ '(1 2 3)) ; 6
(funcall '+ 1 2 3) ; 6