[Haskell-beginners] Easier alternatives to existential types?

Brent Yorgey byorgey at seas.upenn.edu
Thu Nov 26 13:41:41 EST 2009


On Thu, Nov 26, 2009 at 10:01:32PM +0400, Emile Melnicov wrote:
> > Well, yes, I know that almost certanly that was not what you 
> > were thinking when you wrote the question.
> 
> Sorry, I should include my code snippet indeed.
> 
> data Chunk a = Chunk { cHeader :: Header, cData :: a }
> data Header = Header { hID :: Word32, hSize :: Word32 }
> data Format = Format { ... }
> newtype Data = Data ByteString
> 
> h :: Header
> ...
> formatChunk :: Chunk Format
> ...
> dataChunk :: Chunk Data
> ...
> 
> data Container a =
>     Container { ctHeader :: Header, ctType :: Word32,
>                 ctContent :: [Chunk a] }

Do you *really* need 'Chunk' to be able to hold *any* type of data?
Or are there just a few alternatives?  If there are only a few
alternatives, you can put the alternatives together in a data type,
like this:

  data Content = ConH Header
               | ConD Data
               | ... other alternatives ...

  -- Chunk is no longer polymorphic
  data Chunk = Chunk { cHeader :: Header, cData :: Content }

Then you can pattern-match on things of type Content to see which sort
of content it is.  Existential types are not required unless you
really want to be able to put any type of content at all inside a
Chunk.

-Brent


More information about the Beginners mailing list