[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: functional languages ill-suited for large programs?

"Brent Fulgham" <brent.fulgham@xpsystems.com> asks:
> One (probably novice-level) question I have about functional style
> versus Object-Oriented approach is dynamic behavior.  In many
> partial and fully-functional languages, I often see this type of
> construct: 
> (define report-car (x)
>   (if (automobile? x)
>       (display "You are an automobile")
>       (if (truck? x)
>           (display "You are a truck!")
>           ... )))
> In some hypothetical object-oriented language you could do something like:
> class automobile (vehicle) is
>    print-me "I am a car"
> class truck (vehicle) is
>    print-me "I am a truck"
> function report-car (vehicle v) {
>    v.print-me()
> }
> ...
> How can you accomplish this using something like Haskell or ML?  Do
> they provide sufficient dynamic dispatch to allow this kind of
> activity?

Use a type class (Haskell) or a functor (ML).  But you wouldn't write
this sort of code in that style at all; vehicle isn't an abstract data
type, it's a bucket of variants, and you would modify the type
declration and fix all the functions which talk about vehicles.

The functional programmers are fond of pointing out a couple of
parallel examples:

1) What if I want to write a function that takes *two* vehicles and
determines if they are similar in some way?

sameSortOfVehicle Car Car = True
sameSortOfVehicle Truck Truck = True
sameSortOfVehicle _     _     = False

[suspend disbelief for the moment, and pretend that the right-hand
sides are a bit less trivial and the objects have a bit more state.]

CLOS has a pretty good answer here.  Alas, CLOS fails the "what code
will be run when I invoke a function" test for programming-language
comprehensibility---and also makes it hard to write slightly more
fiddly functions:

peculier Car _ = Car
peculier _ Truck = Truck
peculier _ _      = error "Ack!"

How would you write the above in CLOS?  How would you explain it?

2) What if I want to write new functions like sameSortOfVehicle?  Some
   OO languages allow you to add methods to an existing class, some do
   not.  Usually we end up using the visitor pattern.  Functional
   programmers would argue that this compensates for the lack of a
   decent "case" expression, and is far less comprehensible than
   pattern matching.

The fact is that the languages have dramatically different coding
styles and idioms.  Each includes ugly things which are simple in the

-Jan-Willem Maessen