Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can generate the instances in scope for a given type class using Template Haskell.</p> <pre><code>import Language.Haskell.TH -- get a list of instances getInstances :: Name -&gt; Q [ClassInstance] getInstances typ = do ClassI _ instances &lt;- reify typ return instances -- convert the list of instances into an Exp so they can be displayed in GHCi showInstances :: Name -&gt; Q Exp showInstances typ = do ins &lt;- getInstances typ return . LitE . stringL $ show ins </code></pre> <p>Running this in GHCi:</p> <pre><code>*Main&gt; $(showInstances ''Num) "[ClassInstance {ci_dfun = GHC.Num.$fNumInteger, ci_tvs = [], ci_cxt = [], ci_cls = GHC.Num.Num, ci_tys = [ConT GHC.Integer.Type.Integer]},ClassInstance {ci_dfun = GHC.Num.$fNumInt, ci_tvs = [], ci_cxt = [], ci_cls = GHC.Num.Num, ci_tys = [ConT GHC.Types.Int]},ClassInstance {ci_dfun = GHC.Float.$fNumFloat, ci_tvs = [], ci_cxt = [], ci_cls = GHC.Num.Num, ci_tys = [ConT GHC.Types.Float]},ClassInstance {ci_dfun = GHC.Float.$fNumDouble, ci_tvs = [], ci_cxt = [], ci_cls = GHC.Num.Num, ci_tys = [ConT GHC.Types.Double]}]" </code></pre> <p>Another useful technique is showing all instances in scope for a given type class using GHCi.</p> <pre><code>Prelude&gt; :info Num class (Eq a, Show a) =&gt; Num a where (+) :: a -&gt; a -&gt; a (*) :: a -&gt; a -&gt; a (-) :: a -&gt; a -&gt; a negate :: a -&gt; a abs :: a -&gt; a signum :: a -&gt; a fromInteger :: Integer -&gt; a -- Defined in GHC.Num instance Num Integer -- Defined in GHC.Num instance Num Int -- Defined in GHC.Num instance Num Float -- Defined in GHC.Float instance Num Double -- Defined in GHC.Float </code></pre> <p>Edit: The important thing to know is that the compiler is only aware of type classes in scope in any given module (or at the ghci prompt, etc.). So if you call the <code>showInstances</code> TH function with no imports, you'll only get instances from the Prelude. If you have other modules in scope, e.g. Data.Word, then you'll see all those instances too.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload