Lecture 22
Composing Code and Data with Methods
Programming as com/position
Programming as com/position
Subtyping helped us streamline our program
(define (zoo-weight zoo)
(cond [(empty? zoo) 0]
[else (+ (local [(define a (first zoo))]
(cond [(snake? a) (snake-weight a)]
[(dillo? a) (dillo-weight a)]
[(ant? a) (ant-weight a)]))
(zoo-weight (rest zoo)))]))
VS
(define (zoo-weight zoo)
(cond [(empty? zoo) 0]
[else (+ (animal-weight (first zoo))
(zoo-weight (rest zoo)))]))
But what if this was more about an action?
(define (feed-animal! a)
(set-animal-weight! a (+ 2 (animal-weight a))))
(define (feed-zoo! loa)
(for-each (λ (a) (feed-animal! a))
loa))
This isn't an inheritance issue
Methods
Specifying methods in ASL structs
(define-struct (cat animal) (sleeping-spot)
#:methods
(define (feed! c) ...))
(define-struct (dog animal) (best-friend)
#:methods
(define (feed! d) ...))
(define-struct (mouse animal) (hiding-spot)
#:methods
(define (feed! m) ...))
Specifying methods in ASL structs
(define-struct (cat animal) (sleeping-spot)
#:methods
(define (feed! c) ...))
(define-struct (dog animal) (best-friend)
#:methods
(define (feed! d) ...))
(define-struct (mouse animal) (hiding-spot)
#:methods
(define (feed! m) ...))
Specifying methods in ASL structs
(define-struct (cat animal) (sleeping-spot)
#:methods
(define (feed! c) ...))
(define-struct (dog animal) (best-friend)
#:methods
(define (feed! d) ...))
(define-struct (mouse animal) (hiding-spot)
#:methods
(define (feed! m) ...))
Method inheritance
Specifying methods in ASL structs
(define-struct animal (name weight age)
#:methods
(define (feed! a) ...))
(define-struct (cat animal) (sleeping-spot)
#:methods
(define (feed! c) ...))
(define-struct (dog animal) (best-friend)
#:methods
(define (feed! d) ...))
(define-struct (mouse animal) (hiding-spot))
Methods with multiple arguments
Missing methods
(define-struct animal (name weight age)
(define-struct (cat animal) (sleeping-spot)
#:methods
(define (feed! c) ...))
(define-struct (dog animal) (best-friend)
#:methods
(define (feed! d) ...))
Program Design
(define-struct animal (name weight age)
(define-struct (cat animal) (sleeping-spot)
#:methods
(define (feed! c) ...))
(define-struct (dog animal) (best-friend)
#:methods
(define (feed! d) ...))
Abstract Types
(define-struct animal (name weight age)
(define-struct (cat animal) (sleeping-spot)
#:methods
(define (feed! c) ...))
(define-struct (dog animal) (best-friend)
#:methods
(define (feed! d) ...))
Abstract Types
(Note: while some languages call these abstract types, some others use this same term for a totally different concept. Just like everything else in life…there's never anything everyone agrees on).
A very rough analogy
animal
fish
cat
bird
living-thing
plant
This is a whole new approach to program design