how to check if a particular literal belongs to a typeclass or not in haskell

StackOverflow https://stackoverflow.com/questions/23644126

  •  22-07-2023
  •  | 
  •  

Вопрос

I want to check whether a literal value -1 conforms to Eq Typeclass or not in haskell. What is the easiest way to test this.

Это было полезно?

Решение

This is a slightly confusing question, as "I want to check" hints that you might want to find this out dynamically.

Haskell will check all types at compile time, including membership of typeclasses. So to check if a literal is of a type that supports Eq, you simply need to use it with (==) or (/=) and try to compile it.

If you are just exploring which types have Eq instances, check the :info command in GHCi:

Prelude> let x = 1
Prelude> :info x
x :: Integer    -- Defined at <interactive>:1:5

Prelude> :info 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.Num
instance Eq Integer -- Defined in GHC.Classes
instance Integral Integer -- Defined in GHC.Real
instance Num Integer -- Defined in GHC.Num
instance Ord Integer -- Defined in GHC.Classes
instance Read Integer -- Defined in GHC.Read
instance Real Integer -- Defined in GHC.Real

Prelude> :info Eq
class Eq a where
  (==) :: a -> a -> Bool
  (/=) :: a -> a -> Bool
        -- Defined in GHC.Classes
instance Eq a => Eq (Maybe a) -- Defined in Data.Maybe

Другие советы

The literal -1 can be any concrete type like Int or Integer, Float etc. One way to see the types typeclass would be like this:

λ> let a = -1 :: Int
λ> :i 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.Classes'
instance Integral Int -- Defined in `GHC.Real'
instance Num Int -- Defined in `GHC.Num'
instance Ord Int -- Defined in `GHC.Classes'
instance Read Int -- Defined in `GHC.Read'
instance Real Int -- Defined in `GHC.Real'
instance Show Int -- Defined in `GHC.Show'

Another way would be to see, which typeclass can represent -1:

λ> :t (-1)
(-1) :: Num a => a

So, Num typeclass can represent -1.

λ> :i 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'

And types like Int, Integer are instances of it. To see if those types instantiate any other typeclass, just run an info on that type.

The easiest way is to let the compiler check this for you. If you assume that the type implements Eq, then any inferred types will automatically get the Eq constraint. Then if you ever try to use the values with a type that doesn't implement Eq, your program will fail to compile.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top