[Haskell-cafe] Type synonyms vs standard types

wren ng thornton wren at freegeek.org
Wed Sep 30 00:47:15 EDT 2009


Olex P wrote:
> This idea with new level of abstraction is good but in some cases it can
> make things overcomplicated / less efficient. Does that mean "leave simple
> built-in types as is"?

That's what newtypes are for. A newtype is like a type alias, except 
that it is type checked. All newtype wrappering/unwrappering is compiled 
away so the representations are the same. The only performance 
difference is (== should be) that there can be overhead for strange ways 
of providing typeclass instances.[1]



[1] By "strange ways" of providing typeclass instances I mean things 
like using

     class    Peano p where ...

     data     Z   = Z
     newtype  S n = S n
     instance Peano Z                where ...
     instance Peano n => Peano (S n) where ...

instead of a straightforward

     data     ZorS       = Z | S Peano
     instance Peano ZorS where ...

Because of the newtype, the representation of (S n) is the same as the 
representation of Z, thus all peano numbers are the same size. However, 
we still need to keep that info around somewhere, and consequently the 
size of the (Peano n) dictionary is linear in n (because it needs a 
pointer to the (Peano (n-1)) dictionary, and so on until (Peano Z)).

On the other hand, with the straightforward version, the size of (n :: 
ZorS) is linear in n, but the size of the (Peano ZorS) dictionary is 
constant.

-- 
Live well,
~wren


More information about the Haskell-Cafe mailing list