Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find all types that are instances of a typeclass

learnyouahaskell mentions the following:

Types in Enum class are

(), Bool, Char, Ordering, Int, Integer, Float and Double

Is there any way to find which types are instances of which typeclass and vice versa in GHCi?

I want something like the :t that we use in GHCi to find the type of a expression.

like image 997
user1308560 Avatar asked Sep 21 '12 03:09

user1308560


1 Answers

Sure.

For a type class:

Prelude> :i Enum
class Enum a where
  succ :: a -> a
  pred :: a -> a
  toEnum :: Int -> a
  fromEnum :: a -> Int
  enumFrom :: a -> [a]
  enumFromThen :: a -> a -> [a]
  enumFromTo :: a -> a -> [a]
  enumFromThenTo :: a -> a -> a -> [a]
    -- Defined in `GHC.Enum'
instance Enum Ordering -- Defined in `GHC.Enum'
instance Enum Integer -- Defined in `GHC.Enum'
instance Enum Int -- Defined in `GHC.Enum'
instance Enum Char -- Defined in `GHC.Enum'
instance Enum Bool -- Defined in `GHC.Enum'
instance Enum () -- Defined in `GHC.Enum'
instance Enum Float -- Defined in `GHC.Float'
instance Enum Double -- Defined in `GHC.Float'

For a type:

Prelude> :i Integer
data Integer
  = integer-gmp:GHC.Integer.Type.S# GHC.Prim.Int#
  | integer-gmp:GHC.Integer.Type.J# GHC.Prim.Int# GHC.Prim.ByteArray#
    -- Defined in `integer-gmp:GHC.Integer.Type'
instance Enum Integer -- Defined in `GHC.Enum'
instance Eq Integer -- Defined in `integer-gmp:GHC.Integer.Type'
instance Integral Integer -- Defined in `GHC.Real'
instance Num Integer -- Defined in `GHC.Num'
instance Ord Integer -- Defined in `integer-gmp:GHC.Integer.Type'
instance Read Integer -- Defined in `GHC.Read'
instance Real Integer -- Defined in `GHC.Real'
instance Show Integer -- Defined in `GHC.Show'
instance Ix Integer -- Defined in `GHC.Arr'

Unfortunately, this is limited to identifiers, not expressions. So you can't look up, say, what instances apply to a type like [Char] directly.

Also, note that it will only show instances and types that are in scope, so you may need to import stuff you're curious about.

like image 119
C. A. McCann Avatar answered Oct 15 '22 19:10

C. A. McCann