Convert an untyped DSL view to a typed view

Given a simple language, let's say

data E where
  ValE :: Typeable a => a -> E
  AppE :: E -> E -> E

Is it possible to convert it to a typed representation:

data T a where
  ValT :: Typeable a => a -> T a
  AppT :: T (a -> b) -> T a -> T b
  deriving Typeable

I tried various approaches, for example. following:

e2t :: Typeable a => E -> Maybe (T a)
e2t (ValE x) = cast (ValT x)
e2t (AppE e1 e2) = liftM2 AppT (e2t e1) (e2t e2)

This does not work, and I get the following error message:

Undefined variable of type 'a' in constraint:
'Typeable a'
arising from the use of 'e2t' in ...
Probable fix: add a type signature that corrects these type variables

However, if I like it

e2t :: Typeable a => E -> Maybe (T a)
e2t (ValE x) = cast (ValT x)
e2t (AppE e1 e2) = liftM2 AppT (e2t e1) (e2t e2 :: Maybe (T Int))

it compiles.

+5
source share
1 answer

. , . f x GADT, . f :: Bool -> Int x :: Bool, f :: (Int -> Int) -> Int x :: Int -> Int .. , , , Typeable ( , , Typeable).

e2t , . - , . , , - , :

e2t :: E -> Maybe (exists a. T a)

, E , , , , . , , , . :

data AnyT where
    AnyT :: Typeable a => T a -> AnyT

, , , . , , Data.Typeable. - dynApp Data.Dynamic, T Haskell. TypeRep, - "just trust me" unsafeCoerce, , . , .

Agda, TypeRep . , , .

+2

All Articles