[Haskell-cafe] Polymorphism overhead

Don Stewart dons at galois.com
Tue Feb 17 16:06:56 EST 2009


wasserman.louis:
> 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?
> 

In general, INLINE or SPECIALIZE

-- Don


More information about the Haskell-Cafe mailing list