[Haskell-cafe] Polymorphism overhead

Louis Wasserman wasserman.louis at gmail.com
Tue Feb 17 16:04:28 EST 2009


I have (roughly) the following code:

data Foo e
type MFoo e = Maybe (Foo e)

instance Ord e => Monoid (Foo e) where
f1 `mappend` f2 = <code invoking the mappend instance from Maybe (Foo e)>

I'd expect this to optimize to the same thing as if I had implemented:
meld :: Ord e => Foo e -> Foo e -> Foo e
f1 `meld` f2 = -- code invoking meld'

meld' :: Ord e => Maybe (Foo e) -> Maybe (Foo e) -> Maybe (Foo e)
meld' (Just f1) (Just f2) = meld f1 f2
meld' m1 Nothing = m1
meld' Nothing m2 = m2

instance Ord e => Monoid (Foo e) where
 mappend = meld

However, GHC's Core output tells me that the first piece of code reexamines
the polymorphism in every recursion, so that mappend, which is used in the
Monoid instance of Foo, looks up the Monoid instance of Foo *again* (for the
sole purpose of looking itself up) and recurses with that.  Why is this, and
is there a way to fix that?


Louis Wasserman
wasserman.louis at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20090217/1ba16730/attachment-0001.htm


More information about the Haskell-Cafe mailing list