haskellghci

Haskell data types with type variables


I have been going through tutorial examples for data types and I have defined the following:

ghci> data Animal a b = Cat a | Dog b | Rat
ghci> data BreedOfCat = Siamese | Persian | Moggie
ghci> :t Cat Siamese
Cat Siamese :: Animal BreedOfCat b
ghci> :t Cat Persian
Cat Persian :: Animal BreedOfCat b
ghci> :t Dog 12
Dog 12 :: Num b => Animal a b
ghci> :t Dog "Fifo"
Dog "Fifo" :: Animal a String
ghci> :t Rat
Rat :: Animal a b

If Dog "Fifo" gives Animal a String, why doesn't Dog 12 give Animal a Integer (which is what the tutorial says it should)


Solution

  • It basically does. It just does not pick a specific type for the 12, this can be any type that is a member of the Num typeclass, hence Num b => Animal a b. If you force to pick an Integer for 12, it will, indeed:

    ghci> :t Dog (12 :: Integer)
    Animal a Integer