这是一个带有一些额外输入但没有反引号的 hacky 解决方案!我首先在reddit上发布了这个,如果可以的话。
我假设你已经导出Enum
了 for Rank
。
data OF = OF
ace :: OF -> Suit -> PokerCard
ace _ s = PokerCard Ace s
-- or point-free
two :: OF -> Suit -> PokerCard
two _ = PokerCard Two
-- or with const
three :: OF -> Suit -> PokerCard
three = const (PokerCard Three)
-- you get the idea!
-- the rest in one line:
four,five,six,seven,eight,nine,ten,jack,king :: OF -> Suit -> PokerCard
[four,five,six,seven,eight,nine,ten,jack,king] = map (const . PokerCard) [Four .. King]
-- now you can write
pokerDeck = [
ace OF Spades, two OF Spades -- and so on
]
OF 数据类型不是绝对必要的,但可以防止混淆(但非常金属)的东西,例如ace "Motorhead" Spades
. 你仍然可以写ace undefined Spades
,我认为真的没有办法。
如果of
不是关键字,你甚至可以写of = OF
.
还有一个非常邪恶的黑客可以完全摆脱'of',并使用数字作为卡片:
{-# LANGUAGE FlexibleInstances #-} -- this goes on top of your file
instance Num (Rank -> Suit) where
fromInteger n = (undefined : map Card[Ace .. King]) !! (fromInteger n)
现在2 Spades :: Card
类型检查(但您需要显式类型!)并且是您认为的那样:-) 但是,我强烈建议您不要在严肃的代码中这样做;但它看起来很酷。