[Haskell-beginners] Haskell wants the type, but I only know the class.

Antoine Latter aslatter at gmail.com
Fri Nov 4 13:06:43 CET 2011


On Fri, Nov 4, 2011 at 4:40 AM, Amy de Buitléir <amy at nualeargais.ie> wrote:
> I could put a header in the file that tells me what the type of the object is.
> Then I would know at run-time (but not compile-time). Would that help?
>

A really simple and common way to do this would be using a sum-type:

data TypeOne = ...
data TypeTwo = ...
data TypeThree = ...

data AllOfTheTypes = T1 TypeOne
   | T2 TypeTwo
   | T3 TypeThree

instance Binary AllOfTheTypes where
  put (T1 x) = putWord8 0; put x
  put (T2 x) = putWord8 1; put x
  put (T3 x) = putWord8 2; put x

  get = do
    tag <- getWord8
    case tag of
      0 -> T1 <$> get
      1 -> T2 <$> get
      2 -> T3 <$> get

Antoine



More information about the Beginners mailing list