Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does GHC optimize the monoid operation over mempty?

If I write an instance of Semigroup with a horrible complexity for its operation (<>), will GHC know that

mempty <> x = x
x <> mempty = x

and avoid computing (<>) ?

I’m also interested in how you got that information, and, if this optimization does not exits, whether this could be done or has been discussed previously.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

No, for several reasons. First, you don’t have to write lawful Semigroup instances. x <> y = x is a valid definition as far as the compiler is concerned, and it has to generate code that matches the behavior you specify. So there can be no such optimization for every Semigroup.

GHC also can’t in general know whether some value is equal to mempty or not, except by testing it, which it could only do given an Eq instance. But it’s not going to go inserting implicit (==) tests around every Semigroup operation just to avoid calling your (<>) implementation. If you have a specific Semigroup type that you think will perform better if you check for mempty before doing the main work of (<>), you can insert that in the Semigroup instance yourself.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading