Wednesday, January 14, 2009

You say ‘ad hoc’ as if it were a bad thing.

The term ad hoc is a Latin phrase meaning ‘for this purpose’. In 1967, Christopher Strachey used the term to differentiate the kind of polymorphism where a function acts differently on different types from the kind of polymorphism where a generalized function can be parameterized by a range of types. The generic functions of CLOS are a good example of ad hoc polymorphism, and Java ‘generics’ are an example of parameterized polymorphism.

The whole point of generic functions is to allow you to treat objects of different types in a uniform, abstract manner. Generic arithmetic is the motivating example: you want to add two numbers and you really don't care whether they are floating point, integers, rationals, bignums, or whatever, just add the things, ok? Both parametric and ad hoc polymorphism allow you to do this.

Ad hoc is often used to imply something beyond the Latin meaning of specific purpose. It can mean ‘jury-rigged’, ‘makeshift’, ‘spur of the moment’, or ‘not well thought out’. In Wadler and Blott's paper “How to make ad-hoc polymorphism less ad-hoc”, they state:
One widely accepted approach to parametric polymorphism is the Hindley/Milner type system... On the other hand, there is no widely accepted approach to ad hoc polymorphism, and so its name is doubly appropriate.
It is clear that Wadler and Blott are assuming a perjorative meaning.

But what is the problem with ad hoc polymorphism? The primary problem seems to be that unrestricted use of ad hoc polymorphism makes it impossible to fully type check at compile time and requires some sort of run time type dispatch.

Suffice it to say that I'm underwhelmed by this argument.

I have found that parametric polymorphism is a fine tool for the problems it is designed to solve, but ad hoc polymorphism can solve those problems, too. Furthermore, ad hoc polymorphism allows you to do things that are quite difficult to do with parametric polymorphism, for example, add methods to null or other built-in classes, or make universal constructors (compare make-instance to the plethora of Java ‘factory’ classes).

I like ad hoc polymorphism. It allows me to tailor a solution to exactly solve a specific problem, and so its name is singularly appropriate.

4 comments:

Paul Steckler said...

If you couldn't fully typecheck your ad hoc polymorphism, well, it just wouldn't be Haskell-y.

Maybe that's a good thing!

Unknown said...

Do you have the Strachey article? Does he spell ad hoc with or without a dash?

Joe Marshall said...

I think it might have come from Strachey's Copenhagen lectures in 1967. I've only seen it with a hyphen, but then I don't recall hyphen's being in Latin.

Joe Marshall said...

[Strachey 67] C. Strachey. Fundamental Concepts in programming languages.
Lecture Notes for International Summer School in Computer Programming,
Copenhagen, Aug.
Contains original, classical definition of polymorphism.