Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I typecheck custom datatypes in Haskell?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading