获取类型中的值列表

时间:2016-12-17 01:56:44

标签: haskell

在Haskell中,是否可以动态获取类型中的值列表?一个具体的例子是通过组合每个等级和套装中的一个来生成一整套扑克牌,以创建一张牌列表:

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 --

如果没有硬编码值,这将如何实现呢?

1 个答案:

答案 0 :(得分:2)

在这种情况下,最简单的方法是让编译器通过派生的foreach (Reservation i in con.Reservations) { var user = con.Users.Where(se => se.id == i.user_id).FirstOrDefault(); if (i.date == date && i.hour == label4.Text ) { label4.Text = user.Name + " " + user.Surname; } else { label4.Text = "17:00 - 18:00"; } if (i.date == date && i.hour == label5.Text) { label5.Text = user.Name + " " + user.Surname; } else { label5.Text = "16:00 - 17:00"; } if (i.date == date && i.hour == label6.Text) { label6.Text = user.Name + " " + user.Surname; } else { label6.Text = "18:00 - 19:00"; } if (i.date == date && i.hour == label7.Text) { label7.Text = user.Name + " " + user.Surname; } else { label7.Text = "19:00 - 20:00"; } } 实例生成代码。

Enum

或列表理解版本:

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