Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Figuring out a Type Synonym's Type

Tags:

haskell

I made a type synonym in Haskell:

Prelude> type Foo a = [a]

Then, I checked its type:

Prelude> :t [5] :: Foo Integer
[5] :: Foo Integer :: Foo Integer

Of course I know that Foo a is a type synonym for [a] since I just wrote it.

But, if I were consuming a library that returned Foo Integer, how would I know what Foo is?

I tried :t Foo without success.

like image 878
Kevin Meredith Avatar asked Sep 07 '14 13:09

Kevin Meredith


1 Answers

Try this: :i Foo

:i gives information about a bound symbol.
:t gives type signature for expressions. (which is why it didn't work for you - Foo is not an expression, like a function or a value is).

Example:

ghci> :i String
type String = [Char]    -- Defined in ‘GHC.Base’

And here's bonus information:

:i is also awesome for ADTs, it will give you the constructors + tell you which instances they derive (from the imported modules, of course). For example:

ghci> :i Bool
data Bool = False | True    -- Defined in ‘GHC.Types’
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’

And it's also awesome for type-classes, for example:

ghci> :i Monad
class Monad (m :: * -> *) where
  (>>=) :: m a -> (a -> m b) -> m b
  (>>) :: m a -> m b -> m b
  return :: a -> m a
  fail :: String -> m a
    -- Defined in ‘GHC.Base’
instance Monad Maybe -- Defined in ‘Data.Maybe’
instance Monad (Either e) -- Defined in ‘Data.Either’
instance Monad [] -- Defined in ‘GHC.Base’
instance Monad IO -- Defined in ‘GHC.Base’
instance Monad ((->) r) -- Defined in ‘GHC.Base’

And, as mentioned, can also be used for functions:

ghci> :i id
id :: a -> a    -- Defined in ‘GHC.Base’

It is almost exactly like :t, only that it will also tell you in what module the symbol is defined.

So why use :t? it's more flexible. :i only works for bound symbols. E.g. :t (+5) is valid. :i (+5) is not.

like image 164
MasterMastic Avatar answered Sep 27 '22 19:09

MasterMastic