;;; mylisp - Lisp Study Lab 2 - Examples of apply, lambda, assoc, mapcar ;;; Copy this file to your own directory. ;;; Follow the instructions on the course page for running ;;; lisp while in the emacs editor. ;;; Try evaluating each of these expressions by placing the ;;; cursor to the right of the expression and typing ;;; control-x control-e. By the end of this course, you ;;; should be able to figure out what each expression evaluates ;;; to without running lisp!! (defun cube (x) (* x x x)) (cube 2) ; 8 (defun sqr (x) (* x x)) (sqr 2) ; 4 ;; a different way to call the cube function: (apply 'cube '(2)) ; 8 ;; passing functions as arguments: (defun sum-power (f a b) ; f(a) + f(b) (+ (apply f (list a)) (apply f (list b)))) (sum-power 'cube 2 1) ; 9 (sum-power 'sqr 2 1) ; 5 ;; function call using an anonymous function: ((lambda (x) (* x x x)) 2) ; 8 (setq groceries '((dairy milk) (fruit apple) (starch bread) (fruit pear))) (assoc 'fruit groceries) ; (fruit apple) (defun is-fruit (x) (equal 'fruit (car x))) (is-fruit (car groceries)) ; nil (is-fruit (car (cdr groceries))) ; t ; applying function is-fruit to each element of groceries: (mapcar 'is-fruit groceries) ; (nil t nil t) ; applying anonymous function to groceries: (mapcar #'(lambda (x) (equal 'fruit (car x))) groceries) ; (nil t nil t) (defun fruit-points (x) (cond ((is-fruit x) 1) (t 0))) (fruit-points (car groceries)) ; 0 (fruit-points (car (cdr groceries))) ; 1 (mapcar 'fruit-points groceries) ; (0 1 0 1) (apply '+ (mapcar 'fruit-points groceries)) ; 2