[Haskell-cafe] Generic types

robert dockins robdockins at fastmail.fm
Mon Jun 13 16:11:08 EDT 2005

> I'm writing a small unit library to excercise my barely existing 
> Haskell skills.
> However I can't figure out how to make Haskell accept any type 
> of a specific class.


What you want is a technique called "existential types".  The wiki page 
is here: http://haskell.org/hawiki/ExistentialTypes

The problem with existentials is that they are pretty picky about how 
you use them; I'm pretty sure you can't create a labeled record 
containing existentials (because the accessor functions aren't allowed 
to exist).  You have to pattern match to get at the encapsulated value.
Also, once you have done the pattern match on the "UnitValue," you can 
only use polymorphic functions on the pattern variables.

The following does what I think you want.

{-# OPTIONS -fglasgow-exts  #-}

class Unit u where
     shortName :: u -> String

data Meter = Meter

instance Unit Meter where
     shortName u = "m"

data UnitValue = forall u n. (Unit u,Num n) => UnitValue u n

main = let x = UnitValue Meter 10
        in case x of
             UnitValue unit magnitude -> putStrLn $ (show 
magnitude)++(shortName unit)

More information about the Haskell-Cafe mailing list