;; C311 Programming Languages ;; Dana Vrajitoru ;; A small example used in class ;; Examples of function indirection (fset 'first (symbol-function 'car)) # (first '(1 2 3)) 1 (fset 'xfirst 'car) car (xfirst '(1 2 3)) 1 (fset 'yfirst 'xfirst) xfirst (yfirst '(1 2 3)) 1 (fset 'first 'yfirst) yfirst (fset 'xfirst 'first) first (yfirst '(1 2 3)) (defun g (x) (* x x)) g (fset 'g2 (symbol-function 'g)) (lambda (x) (* x x)) ;; First version of the function that copies a list using a recursive ;; call. (defun copy (L) (let ((C '()) (N nil)) (setq C (cond ((not L) nil) ((not (cdr L)) (list (car L))) (t (setq N (copy (cdr L))) (push (car L) N)))) )) (setq M '(1 2 3)) (1 2 3) (copy '()) nil (copy M) (1 2 3) (eq M (copy M)) nil ;; Second implementation of the function copy-list using a dolist ;; loop. (defun copy1 (L) (let ((C '())) (dolist (x L C) (setq C (append C (list x)))))) (copy1 '()) nil (copy1 M) (1 2 3) ;; Third implementation of the function copy-list using mapcar and a ;; simple lambda expression for the identity function. (defun copy2 (L) (mapcar (lambda (x) x) L)) copy2 (copy2 M) (1 2 3) (copy2 '()) nil (eq M (copy2 M)) nil ;; Another example where we use a recursive call and make a deep copy ;; of the list. (defun copy3 (L) (mapcar (lambda (x) (if (listp x) (copy3 x) x)) L)) (setq M '(1 2 (3 4) 5)) (copy3 M) (1 2 (3 4) 5) ; Note that copy3 make a hard copy of the list nested inside (eq (car (cdr (cdr M))) (car (cdr (cdr (copy3 M))))) nil ; while copy2 just makes a reference to the same list inside (eq (car (cdr (cdr M))) (car (cdr (cdr (copy2 M))))) t