[Haskell-cafe] reading existential types

Claus Reinke claus.reinke at talk21.com
Mon Jul 9 11:28:43 EDT 2007


> I'd like to be able to use MT to build a list like:
> [MT (T1a,1), MT (T1b,3)]
> And I'd like to read str with:
> read $ show str
 
> Substituting return (m) with return (MT m) leads to error messages
> like: Ambiguous type variable `e' in the constraints

which is the important hint! the parser used for 'read' depends on
the return type, but the existential type _hides_ the internal type
which would be needed to select a read parser.
 
> readMT :: ReadPrec MyType
> readMT = prec 10 $ do
>           Ident "MT" <- lexP
>           parens $ do m <- readPrec
>                       return (m) 

if your hidden types have distinguishable 'show'-representations,
you could write your own typecase like this (making use of the
fact that 'read' parsers with incorrect type will fail, and that the
internal type can be hidden after parsing)

    readMT :: ReadPrec MyType
    readMT = prec 10 $ do
           Ident "MT" <- lexP
           parens $ (do { m <- readPrec; return (MT (m::(TipoA,Int))) })
            `mplus` (do { m <- readPrec; return (MT (m::(TipoB,Int))) })

    *Test> read (show [MT (T1a,1),MT (T1b,3)]) :: [MyType]
    [MT (T1a,1),MT (T1b,3)]

(if necessary, you could have 'show' embed a type representation 
for the hidden type, and dispatch on that representation in 'read')

claus



More information about the Haskell-Cafe mailing list