;; ;; example of a polymorphic function and "tagged" data ;; ;; $ scheme types.scm ;; (add (point 1 2) (point 5 6)) is (point 6 8). ;; (add 2.3 5.6) is 7.8999999999999995. ;; ;; Jim Mahoney | cs.bennington.college | Oct (define (make-point x y) (list 'point x y)) (define (x-point p) (cadr p)) ;; 2nd element of list (define (y-point p) (caddr p)) ;; 3rd element of list (define (point? p) ;; is p a point ? (and (pair? p) (eq? (car p) 'point))) (define (add-point p1 p2) (make-point (+ (x-point p1) (x-point p2)) (+ (y-point p1) (y-point p2)))) (define (add a b) ;; add for numbers or points ;; ... this is a polymorphic function that ;; that can add numbers or points (if (point? a) (add-point a b) (+ a b))) ;; ------------------------------------- ;; adding points (define p1 (make-point 1 2)) (define p2 (make-point 5 6)) (printf "(add ~s ~s) is ~s.\n" p1 p2 (add p1 p2)) ;; adding numbers ... with the same function (define x1 2.3) (define x2 5.6) (printf "(add ~s ~s) is ~s.\n" x1 x2 (add x1 x2))