Reputation: 25
Can someone please explain to me how we can define a new type in terms of itself in Haskell. Below is the snippet of code I am struggling to understand. I do not understand how we can define a new type in terms of itself. We are saying Card
is a new type with constructors Card Rank Suit
. What does this even mean?
Any help would be greatly appreciated.
data Suit = Spades | Hearts | Clubs | Diamonds
deriving (Show, Eq)
data Rank = Numeric Int | Jack | Queen | King | Ace
deriving Show
data Card = Card Rank Suit
deriving Show
Upvotes: 0
Views: 82
Reputation: 120751
We are saying
Card
is a new type with constructorsCard Rank Suit
. What does this even mean?
Well, first of all it's wrong. Card
is a new type with the single constructor Card
; the latter takes two arguments, which are of type Rank
and Suit
.
The confusing thing here is that you're really dealing with two different things that are both called Card
. Let's disambiguate:
data CardT = CardC Rank Suit
deriving Show
That expresses the same definition, but now it's clear that the type and constructor aren't the same thing. CardT
lives in the type-level language, CardC
lives in the value-level language.
> :t CardC
CardC :: Rank -> Suit -> CardT
Upvotes: 2