www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Most elegant representation of a card's rank

reply "deed" <none none.none> writes:
How is a playing card's rank represented most elegantly in code?

* Should be a customized uint/an own type representing uints in 
the range of 2 through 14.
* void foo(Rank rank) {  } // Accepts only the valid range
   foo(0);  // Error
   foo(2);  // Ok
   foo(10); // Ok

   alias J 11;
   alias Q 12;
   etc.,

   foo(J);  // Ok
   foo(Q);  // Ok
   foo(B);  // Error
Dec 03 2012
next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
deed:

 How is a playing card's rank represented most elegantly in code?

Maybe with an enum? enum Card { J, Q, ...} If you have to store many of them then maybe giving them a size of one byte is better: enum Card : ubyte { Ace, Two, ..., Q, ...} Bye, bearophile
Dec 03 2012
prev sibling next sibling parent "deed" <none none.none> writes:
On Monday, 3 December 2012 at 23:42:38 UTC, bearophile wrote:
 deed:

 How is a playing card's rank represented most elegantly in 
 code?

Maybe with an enum? enum Card { J, Q, ...} If you have to store many of them then maybe giving them a size of one byte is better: enum Card : ubyte { Ace, Two, ..., Q, ...} Bye, bearophile

Using enum Rank { J=11, Q, K, A } doesn't enable the function signature to be foo(Rank rank) when calling with 2, 3, .. 10, right? And using enum Rank { two, three, four, ... , K, A } is not elegant. I'd like to be able to call foo(Rank rank) with foo(3) and foo(Q).
Dec 03 2012
prev sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
deed:

 And using enum Rank { two, three, four, ... , K, A } is not 
 elegant.

But it's strongly typed, so it's safere. It's my preferred solution for a problem like this.
 I'd like to be able to call foo(Rank rank) with foo(3) and 
 foo(Q).

Then use module level compile-time constant... Bye, bearophile
Dec 03 2012