简体   繁体   中英

Figuring out a Type Synonym's Type

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.

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. Eg :t (+5) is valid. :i (+5) is not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM