I'm very new to haskell, so sorry in advance.
I'm writing a program thats has a custom type "Rank". (The rank of a blackjack-card)
data Rank = Int | Jack | Queen | King | Ace
data Suit = Club | Diamond | Heart | Spade
data Card = Card Rank Suit
getCardValue :: Card -> Int
getCardValue (Card val _) = valueOfRank val
valueOfRank :: Rank -> Int
valueOfRank (Int i) = i --Doesnt work
valueOfRank Jack = 10
valueOfRank Queen = 10
valueOfRank King = 10
valueOfRank Ace = 11
Now I want to receive the respective value of a card with a function, my problem is, that I dont know how to typecheck if the value is of the type Int.
CodePudding user response:
data Rank = Int | Jack | Queen | King | Ace
The above Int
is a data constructor name, and is completely unrelated to the Int
type. Indeed, Jack
is a similar data constructor but there's no Jack
type around.
If you want a Rank
value actually containing a value of type Int
, you need to use something like
data Rank = I Int | Jack | Queen | King | Ace
Here I
is the constructor name (you can rename it as you wish), and Int
now refers to the type. You can then use Rank
as:
valueOfRank :: Rank -> Int
valueOfRank (I i) = i
valueOfRank Jack = 10
valueOfRank Queen = 10
valueOfRank King = 10
valueOfRank Ace = 11
Note that nothing prevents the programmer to abuse the I
constructor and create invalid card values like I 123
, I 11
, and I 1
.