r/purescript • • Oct 09 '19

What are the differences between Bounded Parametric Polymorphism and Ad Hoc Polymorphism?

For the longest time I've always associated ad hoc polymorphism with function overloading where the type that's passed in matters because the underlying implementation may be different.

I've associated parametric polymorphism with Generics in other languages as well as functions that can accept any type as the type truly does not matter with respect to how it's used.

However, whenever you place a constraint on a type, it seems to me that the type does matter in the sense that you've narrowed the scope as to what the type can be.

So, is it the case that with bounded parametric polymorphism that the type truly doesn't matter because the usage is going to be the same so long as it meets some constraint?

I'm probably thinking about this incorrectly and have some implicit assumption I'm making that's incorrect but I'm having trouble teasing it out. Let me know if I can clearer. I think the difference has to do with the underlying usage of the type and whether or not it's the same or has to change.

The question is how does bounded parametric polymorphism differ from ad hoc polymorphism?

Thanks in advance!

Edit: Thank you all for the replies! I've got a lot of thinking to do.

8 Upvotes

11 comments sorted by

View all comments

Show parent comment

1

u/benjaminhodgson Oct 10 '19

There is no runtime lookup, no vtable, no set of runtime-level functions involved

This is not really true in Haskell. By default, classy code is compiled to a “dictionary passing” style, which naively does involve runtime lookups. Much of the time GHC can do the required specialisation and inlining to erase the lookups but it will always fall back on code which does runtime work.

the type system ensures that every polymorphic function can be resolved to a concrete function before the program will compile successfully.

This is indeed true of Haskell’s classes, but it’s also true of many object-oriented languages. In Java, for example, if you declare that an object implements a given interface, you have to actually give an implementation for all of that interface’s methods.