CS 2135: Programming Language Concepts
Functional versus OO programming


Recall our boa, armadillo, and animal data definitions from a couple of weeks ago:

;; A boa is a (make-boa symbol number symbol)

(define-struct boa (name length food))

;; An armadillo is a (make-armadillo number boolean)

(define-struct armadillo (length dead?))

;; run-over : armadillo -> armadillo
;; consume an armadillo and return a new one that is dead and is one
;;   unit longer than the input armadillo
(define (run-over adillo)
  (make-armadillo (+ (armadillo-length adillo) 1)
                  true))

;; An animal is either
;;   - a boa, or
;;   - a dillo

;; longer-than? : animal number -> boolean
;; determine whether an animal is longer than a given length
(define (longer-than? ani len)
  (cond [(boa? ani) (> (boa-length ani) len)]
	[(armadillo? ani) (> (armadillo-length ani) len)]))

Let's turn boas and dillos into objects instead of structs:

(define make-boa-obj
  (lambda (name length food)
    (local [(define (longer-than? len) (> length len))]
      (lambda (service)
	(cond [(symbol=? service 'longer-than?) longer-than])))))

(define make-dillo-obj
  (lambda (length dead?)
    (local [(define (longer-than? len) (> length len))]
      (lambda (service)
	(cond [(symbol=? service 'longer-than?) longer-than]
	      [(symbol=? service 'run-over)
	       (make-dillo-obj (+ length 1) true)])))))

Several things to note:

This example shows the natural, direct mapping between the style of code we've been writing in Scheme and OO code. You can take any data definition from this term and turn it into code with objects by:

Moral: functional and OO programs have the same style and structure -- they just organize their code a bit differently! This means that everything you've learned about templates and data definitions in 2135 carries over and applies to programming in mainstream OO languages.


Questions


This page maintained by Kathi Fisler
Department of Computer Science Worcester Polytechnic Institute