如何在Haskell中定义中缀函数?

时间:2013-03-11 19:37:54

标签: function haskell infix-notation

我想将一个函数定义为中缀,这样用户就不必手动用反引号来包围该函数来调用它。具体来说,我正在编写类似DSL的功能,接受排名和套装并构建扑克牌记录:

-- 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,
  ...
  ]

我认为of被保留为case ... of表达式的语法,因此我必须将其重命名为of'.of+of,等

3 个答案:

答案 0 :(得分:10)

无法使用字母数字名称定义函数作为中缀。 Haskell的语法规则只允许使用带有反引号的符号名称或函数名称的函数作为中缀 - 没有办法改变它。

答案 1 :(得分:6)

嗯,您可能已经知道这一点,但(当然)运营商/可以/是中缀。所以你可以r of s拥有r >| s

答案 2 :(得分:6)

这是一个带有一些额外输入的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
   ]

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 typechecks(但你需要显式类型!)并且你认为它是:-)但是,我强烈建议你不要在严肃的代码中这样做;但它看起来很酷。