[Template-haskell] local type declarations

Einar Karttunen ekarttun at cs.helsinki.fi
Wed Nov 24 02:54:06 EST 2004


Hello

Is it possible to create local types with template Haskell?

I would like to create a metafunction like:

withMod :: IVal a => Int -> (MInt a -> MInt a) -> Int -> Int
withMod modulus func param =
    do create a new type T
       create instance IVal T where val _ = modulus
       [| unM $ func (param :: MInt T) |]


This is trying to conquer the limitation of no local class 
instances. Can this be done with TH without resorting to tricks
like generating auxiliary files? 

Here is the context leading to withMod:
-- short modular arithmetic

class IVal a where val :: a -> Int
newtype MInt a = MInt Int deriving (Eq,Show)
unM (MInt v) = v

instance IVal a => Num (MInt a) where
    (MInt a) + (MInt b) = MInt $ (a + b) `mod` val (undefined :: a)
    (MInt a) - (MInt b) = MInt $ (a - b) `mod` val (undefined :: a)
    (MInt a) * (MInt b) = MInt $ (a * b) `mod` val (undefined :: a)
    abs       _   = error "MInt abs not supported"
    signum    _   = error "MInt signum not supported"
    fromInteger i = MInt (fromEnum i)

example :: IVal a => MInt a -> MInt a
example a = a + a

-- expression          => spliced to                   => runtime          
-- withMod 4 example 3 => unM $ func (3 :: MInt T_xyz) => 2

ps. I have read the configurations paper which used to encode the 
value with the typesystem, but am trying to look for a cleaner way.

- Einar Karttunen


More information about the template-haskell mailing list