检查类型是否实例化GHCI中的类型类

时间:2018-08-30 17:20:35

标签: haskell ghci

有没有办法询问GHCi类型是否实例化类型类?我在和^^运算符混在一起,然后输入:

Prelude> :type (^^)
(^^) :: (Integral b, Fractional a) => a -> b -> a

非常有用。然后我想知道Rational是否实例化小数。我在Hoogle上找到了Rational,并取消引用了Ratio,最后发现:

Integral a => Fractional (Ratio a)

有没有更简单的方法?像这样:

:listypeclasses Rational

:listinstances Fractional

2 个答案:

答案 0 :(得分:6)

您要:info,也可以缩写为:i。使用:info <type>列出该类型的实例,或使用:info <class>列出该类的实例。

对于Rational,由于它是类型别名,因此:info不会直接列出实例。但是,它会告诉您这是一个类型别名,您可以通过对别名使用:info来跟踪它:

ghci> :info Ratio
data Ratio a = !a :% !a     -- Defined in ‘GHC.Real’
instance Eq a => Eq (Ratio a) -- Defined in ‘GHC.Real’
instance Integral a => Ord (Ratio a) -- Defined in ‘GHC.Real’
instance Show a => Show (Ratio a) -- Defined in ‘GHC.Real’
instance (Integral a, Read a) => Read (Ratio a)
  -- Defined in ‘GHC.Read’
instance Integral a => Enum (Ratio a) -- Defined in ‘GHC.Real’
instance Integral a => Fractional (Ratio a)
  -- Defined in ‘GHC.Real’
instance Integral a => Num (Ratio a) -- Defined in ‘GHC.Real’
instance Integral a => Real (Ratio a) -- Defined in ‘GHC.Real’
instance Integral a => RealFrac (Ratio a) -- Defined in ‘GHC.Real’

答案 1 :(得分:3)

这是一种方法:

> :set -XFlexibleContexts
> :t undefined :: (Fractional Rational) => Int

<interactive>:1:14: warning: [-Wsimplifiable-class-constraints]
    • The constraint ‘Fractional Rational’
        matches an instance declaration
      instance Integral a => Fractional (GHC.Real.Ratio a)
        -- Defined in ‘GHC.Real’
      This makes type inference for inner bindings fragile;
        either use MonoLocalBinds, or simplify it using the instance
    • In an expression type signature: (Fractional Rational) => Int
      In the expression: undefined :: (Fractional Rational) => Int
undefined :: (Fractional Rational) => Int :: Int

这只是一个警告,因此该实例存在。

> :t undefined :: (Fractional Bool) => Int

<interactive>:1:1: error:
    No instance for (Fractional Bool)
      arising from an expression type signature

这是一个错误,因此没有实例。

(上面的Int是任意的,您可以使用任何其他类型。)