Shane
Shane

Reputation: 1230

Get list of values in type

In Haskell, is it possible to dynamically get a list of values in a type? A specific example is generating a complete deck of playing cards by combining one of each rank and suit to create a list of cards:

data Rank = 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | J | Q | K | A
data Suit = Spades | Hearts | Diamonds | Clubs
data Card = Card Rank Suit

deck :: [Card]
deck = -- get list of ranks and suits to create a deck --

How would this be accomplished without hard-coding values?

Upvotes: 1

Views: 107

Answers (1)

user2297560
user2297560

Reputation: 2983

In this case, the easiest way is getting the compiler to generate the code through a derived Enum instance.

data Rank = Two | Three | Four | Five | Six | Seve | Eight | Nine | Ten | J | Q | K | A
    deriving (Show, Enum, Bounded)

data Suit = Spades | Hearts | Diamonds | Clubs
    deriving (Show, Enum, Bounded)

data Card = Card Rank Suit

deck :: [Card]
deck = do
    rank <- enumFrom minBound :: [Rank]
    suit <- enumFrom minBound :: [Suit]
    return $ Card rank suit

or the list comprehension version:

deck :: [Card]
deck = [Card rank suit | rank <- enumFrom minBound :: [Rank], suit <- enumFrom minBound :: [Suit]]

Upvotes: 2

Related Questions