mca*_*dre 4 haskell function infix-notation
我想将一个函数定义为中缀,这样用户就不必手动用反引号来包围该函数来调用它.具体来说,我正在编写类似DSL的功能,接受Rank和Suit并构建扑克牌记录:
-- pseudocode
data PokerCard = PokerCard { rank :: Rank, suit :: Suit } deriving (Eq)
of :: Rank -> Suit -> PokerCard
r of s = PokerCard { rank = r, suit = s }
pokerDeck = [
Ace of Spades,
Two of Spades,
...
]
Run Code Online (Sandbox Code Playgroud)
我相信,of保留为语法case ... of表达,所以我不得不重新命名它像of',.of,+of等等.
小智 6
好吧,您可能已经知道这一点,但(当然)运营商/可以/是中缀.所以,你可以,而是r of s必须r >| s.
这是一个带有一些额外打字的hacky解决方案,但没有反引号!我首先在reddit上发布了这个,如果没关系的话.
我假设你已经派生Enum了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
]
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
现在2 Spades :: Cardtypechecks(但你需要显式类型!)并且你认为它是:-)但是,我强烈建议你不要在严肃的代码中这样做; 但它看起来很酷.
| 归档时间: |
|
| 查看次数: |
5216 次 |
| 最近记录: |