[Haskell-cafe] Are newtypes optimised and how much?

wren ng thornton wren at freegeek.org
Tue Oct 19 23:43:03 EDT 2010


On 10/19/10 2:12 PM, Christopher Done wrote:
> Questions (I'm talking about GHC when I refer to compilation):
>
> (1) Are fromString and fromIntegral ran at compile time? I don't think
> that this is the case. I think they are just translated to fromString
> "Hello, World!" and fromIntegral 2 verbatim.
> (2) Regardless of this, the implementation of fromString and
> fromIntegral is essentially a no-op, it's just fromString = Foo,
> fromIntegral = Bar, which is in turn essentially fromString = id,
> fromIntegral = id, as far as I understand it.

Foo and unFoo are /essentially/ id, but they're not actually id. In 
particular, they stick around as System Fc coersions in the core 
language, whereas id can be compiled away entirely. Unfortunately this 
means that rewrite rules involving id won't fire, which is why I often 
add things like:

     {-# RULES
     "map Foo"        map   Foo = unsafeCoerce
     "fmap Foo"       fmap  Foo = unsafeCoerce
     "liftA Foo"      liftA Foo = unsafeCoerce
     "liftM Foo"      liftM Foo = unsafeCoerce

     "map unFoo"      map   unFoo = unsafeCoerce
     "fmap unFoo"     fmap  unFoo = unsafeCoerce
     "liftA unFoo"    liftA unFoo = unsafeCoerce
     "liftM unFoo"    liftM unFoo = unsafeCoerce
         #-}

if I want to ensure them. Unfortunately, last I heard the use of 
unsafeCoerce can interfere with other rewrite rules, too, since it's 
also /essentially/ but not exactly id.

I'd love to get an up-to-date story on how exactly newtypes and things 
like fromString, fromInteger, fromEnum, and fromRational are handled re 
how they get optimized in GHC 7.

-- 
Live well,
~wren


More information about the Haskell-Cafe mailing list