Reputation: 4486
I am trying to build a simple ghci-like console using ghc-api. I've gotten to a point where I can extract Type
's of expressions using exprType
and to evaluate them. Is there also an easy way to check if the type of the expression has an instance of a given class?
Edit: It seems that functions I'm looking for would require an InstEnv
, but I have no clue where to find that.
Upvotes: 4
Views: 171
Reputation: 14678
The isInstance
method may do what you require.
Example in ghci:
> :set -XTemplateHaskell
> import Language.Haskell.TH
> $(stringE . show =<< (isInstance ''Functor . (: []) =<< [t| [] |]))
"True"
> $(stringE . show =<< (isInstance ''Show . (: []) =<< [t| Maybe Int |]))
"True"
$(stringE . show =<< (isInstance ''Show . (: []) =<< [t| (Int -> Bool) |]))
"False"
Its type sig is
isInstance :: Name -> [Type] -> Q Bool
Ie you give a name (retrieved using ''
or with the mkName
function) for the class, then you pass the types to check against the class (more than one will be required if the class is a multiparam type class). It will then return True or False in the Q monad.
Upvotes: 3