- Create a new project data-types using Stack new data types. Change into the directory data-types and build the new project using stack build.
In the command prompt, run stack ghci. You will see the prompt. Enter this =:type (5 :: Int) =: command:
*Main Lib> :type (5 :: Int)
(5 :: Int) :: Int
:type is a GHCi command to show the type of the expression. In this case, the expression is 5. It means that the expression (5 :: Int) is Int. Now, enter this :type 5 command:
*Main Lib> :type 5
5 :: Num t => t
- GHCi will interpret 5 as 5 :: Num t => t, which means that Haskell identified 5 as some numerical type t. Num t => t shows that the type is t and that it has an extra qualification, Num. Num t denotes that t is an instance of a type class Num. We will see type classes later. The Num class implements functions required for numerical calculation. Note that the result of :type 5 is different from :type (5::Int).
- Now, enter :type (5 :: Double). You will see (5 :: Double) :: Double. Do the same thing with 5::Float:
*Main Lib> :type (5 :: Double)
(5 :: Double) :: Double
Note the difference between 5, 5::Int, 5::Float, and 5::Double. Without a qualification type (such as :: Int), Haskell interprets the type as a generic type Num t => t, that is, 5 is some type t, which is a Num t or numerical type.
Now enter following boolean types at the prompt:
*Main Lib> :type True
True :: Bool
*Main Lib> :type False
False :: Bool
True and False are valid boolean values, and their type is Bool. In fact, True and False are the only valid Bool values in Haskell. If you try 1 :: Bool, you will see an error:
*Main Lib> 1 :: Bool
<interactive>:9:1: error:
* No instance for (Num Bool) arising from the literal
‘1’
* In the expression: 1 :: Bool
In an equation for ‘it’: it = 1 :: Bool
Haskell will complain that 1 is a numerical type and Bool is not a numerical type, which would somehow represent it (value 1).
- Now, type :type 'C' in the prompt. GHCi will report its type to be 'C' :: Char. Char is another data type and represents a Unicode character. A character is entered within single quotes.
- Get more information about each type. To do this, you can enter :info <type> in the prompt:
*Main Lib> :info Bool
data Bool = False | True
-- Defined in ‘ghc-prim-0.5.0.0:GHC.Types’
instance Bounded Bool -- Defined in ‘GHC.Enum’
instance Enum Bool -- Defined in ‘GHC.Enum’
instance Eq Bool -- Defined in ‘ghc-prim-0.5.0.0:GHC.Classes’
instance Ord Bool -- Defined in ‘ghc-prim-0.5.0.0:GHC.Classes’
instance Read Bool -- Defined in ‘GHC.Read’
instance Show Bool -- Defined in ‘GHC.Show’
This will show more information about the type. For Bool, Haskell shows that it has two values False | True and that it is defined in ghc-prim-0.5.0.0:GHC.Types. Here, ghc-prim is the package name, which is followed by its version 0.5.0.0 and then Haskell tells that GHC.Types is the module in which it is defined.