Question

I have created a data structure for representing playing cards (not sure if it is correct) from a standard deck (52 cards, no jokers). Each card has one of the suits spades, hearts, diamonds or clubs, and one of the ranks ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen, king:

datatype suit = spades | hearts | diamonds | clubs
datatype rank = ace | king | queen | jack | ten | nine | eight | seven | six | five | four | three | two
type playing_card = suit * rank

Next step is to write a function greaterCard that operates on the new data type I just declared above. The function should take two playing cards as arguments. The function should return true if the first card has a higher value than the second card, otherwise false. Ace is considered the highest rank, followed by king, queen, jack, 10, 9, ..., 2. If both cards have the same rank, suits are ordered as follows: spades > hearts > clubs > diamonds.

First of all I made two sub-functions so that every rank and suit gets a value in the form of a integer so that I later can compare these integers to see if one card is greater than the other:

fun value_of_rank rank =                                      
case rank of
   ace => 14
 | king => 13
 | queen => 12
 | jack => 11
 | ten  => 10
 | nine => 9
 ...
 | two => 2 

And:

fun value_of_suit suit =
case suit of
   spades => 4
 | hearts => 3
 | diamonds => 2
 | clubs => 1

How do I proceed from here, and are there any better ways of doing this?

Was it helpful?

Solution

The card comparison requires two stages:

fun compare_cards(c1,c2)
  let val val_c1 = value_of_rank(c1)
      val val_c2 = value_of_rank(c2)
  in 
      if val_c1 = val_c2
      then compare_on_suit
      else compare_on_rank
  end

Also value_of_rank would be more elegant with fewer cases. Consider which cases could be combined.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top