问题
Is it possible to see which typeclasses the type implements? Something like:
>:typeclasses Int
[Num, etc...]
回答1:
Use the :info
command.
Prelude> :info Int
data Int = GHC.Types.I# GHC.Prim.Int# -- Defined in GHC.Types
instance Bounded Int -- Defined in GHC.Enum
instance Enum Int -- Defined in GHC.Enum
instance Eq Int -- Defined in GHC.Base
instance Integral Int -- Defined in GHC.Real
instance Num Int -- Defined in GHC.Num
instance Ord Int -- Defined in GHC.Base
instance Read Int -- Defined in GHC.Read
instance Real Int -- Defined in GHC.Real
instance Show Int -- Defined in GHC.Show
Naturally this list depends on the modules that are currently imported.
Prelude> :info (->)
data (->) a b -- Defined in GHC.Prim
Prelude> :m +Control.Monad.Instances
Prelude Control.Monad.Instances> :info (->)
data (->) a b -- Defined in GHC.Prim
instance Monad ((->) r) -- Defined in Control.Monad.Instances
instance Functor ((->) r) -- Defined in Control.Monad.Instances
回答2:
Try :info
or :i
with the type.
This will get you both the typeclasses and the declaration of the type, as well as telling you were it was defined (which is useful if you don't remember what constructors it has).
For types you define yourself, you even get a link to where it was defined in Emacs. This makes it really convenient to navigate around your source.
Note that :i
is very multipurpose: you can use it on both values and types. So :i True
and :i Bool
both work!
*Main> :i Bool
data Bool = False | True -- Defined in GHC.Bool
instance [overlap ok] Truthy Bool
-- Defined at /home/tikhon/Documents/blarg2.hs:40:10-20
instance Bounded Bool -- Defined in GHC.Enum
instance Enum Bool -- Defined in GHC.Enum
instance Eq Bool -- Defined in GHC.Classes
instance Ord Bool -- Defined in GHC.Classes
instance Read Bool -- Defined in GHC.Read
instance Show Bool -- Defined in GHC.Show
instance Ix Bool -- Defined in GHC.Arr
*Main> :i True
data Bool = ... | True -- Defined in GHC.Bool
It's also very useful for checking the precedence of operators:
*Main> :i +
class (Eq a, Show a) => Num a where
(+) :: a -> a -> a
...
-- Defined in GHC.Num
infixl 6 +
来源:https://stackoverflow.com/questions/9335694/see-which-typeclasses-the-type-is-an-instance-of-in-ghci