[Haskell-cafe] Type vs TypeClass duality
tjay.dreaming at gmail.com
Tue Oct 23 04:09:26 EDT 2007
Following up on my previous thread, I have figured out why it bothered
me that we cannot have a list such as the following: ["abc", 123, (1,
2)] :: Show a => [a]
It seems to me that there is an annoying duality in treating simple
algebraic data type vs type classes. As it stands, I can only have a
list where all the elements are of the same basic, ADT, type. There is
no way to express directly a list where all the elements satisfy a
given type class constraint.
If I am not mistaken, type classes are currently implemented in GHC like so:
Given a function "show" of type Show a => a -> string, and the
expression "show 10", GHC will pass the Int dictionary for class
Show's methods and the integer 10 to the function "show". In other
words, for each type class constraint in the function type, there will
be a hidden dictionary parameter managed entirely by the compiler.
What I find strange is, if we can have functions with hidden
parameters, why can't we have the same for, say, elements of a list?
Suppose that I have a list of type Show a => [a], I imagine that it
would not be particularly difficult to have GHC insert a hidden item
along with each value I cons onto the list, in effect making the
concrete type of the list [(Dictionary Show, a)]. I'm assuming that it
will not be particularly difficult because GHC will know the types of
the values I cons onto it, so it will most definitely be able to find
the Show dictionary implemented by that type, or report a type
mismatch error. No dynamic type information is necessary.
I am not an OO programming zealot, but I'd like to note here that this
is also how (class based) OO languages would allow the programmer to
mix types. e.g. I can have a List<Show> where the elements can be
instances of Show, or instances of subclasses of Show.
Why does this second rate treatment of type classes exist in Haskell?
More information about the Haskell-Cafe