Home > front end >  Haskell: Value of a Card, function
Haskell: Value of a Card, function

Time:11-21

I'm still doing the exercise from the book and the one exercise says that I should create a function: value :: Hand -> Int, which returns the value of the hand.

My code so far looks like this:

data Card = Card Rank Suit 
            deriving (Show)

data Suit = Spade | Heart | Diamond | Club
            deriving (Show, Ord, Eq, Enum)

data Rank = Ace | King | Queen | Jack | Ten | Nine | Eight | Seven
            deriving (Show, Eq, Ord, Enum)

data Hand = PairOf Rank | ThreeOf Rank | Flush Suit
            deriving (Show, Eq)

-- This function implements a value function which returns the value of the hand.
-- Pair (2 cards of the same rank) = 1
-- ThreeOf (3 cards of the same rank) = 2
-- Flush (3 cards of the same suit) = 3
-- Nothing = 0

value :: Hand -> Int
value (PairOf r1) = 1
value (Drilling r1) = 2
value (Flush s1) = 3
otherwise = 0

I now have another problem, because I don't know how to describe "Nothing". Nothing is described here as a possible hand combination in which Pair, ThreeOf and Flush do not occur. Would otherwise = 0 work or doesn't that make much sense?

Thanks again for the suggestions, I corrected them! Thanks also in advance for explanations and help.

CodePudding user response:

otherwise won't work here. What you want is an irrefutable pattern that will match anything, and further since you don't care what gets matched, you specifically want the pattern _:

value :: Hand -> Int
value (PairOf r1) = 1
value (ThreeOf r1) = 2
value (Flush s1) = 3
value _ = 0

Since you don't care about what kind of pair, etc you get, you can also use _ in the other cases:

value :: Hand -> Int
value (PairOf _) = 1
value (ThreeOf _) = 2
value (Flush _) = 3
value _ = 0

If you wanted to match Nothing (or whatever name you come up with that doesn't conflict with the Maybe constructor) specifically, it's just

value Nothing = 0
  • Related