[Haskell-beginners] special polymorphic default of typeclass depending on other typeclasses?
David McBride
toad3k at gmail.com
Thu Jun 29 17:45:14 UTC 2017
This is a common mistake that people who try to use type classes run
into. I remember banging my head against it pretty hard when I first
started out.
There's this temptation that you should be able to write the following:
class Foo a where
bar :: a -> String
instance Read a => Foo a where
bar a = read a
instance Foo () where
bar _ = "bar"
But the problem with that is that now () applies to two conflicting
classes. It is both a Read and a Foo. So when you go bar (), which
instance should fire? The Foo instance or the Read () => Foo
instance?
There are a multitude of ways you could try to resolve this. Let's
say obviously the Read constrainted instance is more specific, we
should use that. But then what if the user of your library happens to
have a instance Ord a => Foo a in his library, now which one of those
is more specific? Read or Ord?
Because of all these ambiguities during type checking ghc doesn't even
look at the constraint. It would see instance Foo a, and instance Foo
(), and then say oh! those are overlapping instances because () could
apply to either class before you consider what constraints apply.
There's actually several very in depth answers on stackoverflow for
this questions like this, such as this one:
https://stackoverflow.com/a/3216937/1500583 It might give you some
ideas on what to do about this.
On Thu, Jun 29, 2017 at 1:15 PM, Silent Leaf <silent.leaf0 at gmail.com> wrote:
> hi,
>
> say i have the following typeclass:
>
> class Foo a where
> bar :: a -> String
>
> looks a lot like the Read typeclass, right? (at least i think it should?)
> well say it's a different meaning (in other terms i can't or do not want to
> use Read, but i'd like to implement a default version of bar for those
> instances that also implement Read. is there a way to do so?
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>
More information about the Beginners
mailing list