Haskell 创建中缀函数
我可以定义这样的函数Haskell 创建中缀函数,haskell,Haskell,我可以定义这样的函数 method1 :: Int -> Int -> Int method1 a b = a + b main = print $ 1 `method1` 2 如果我不想每次调用函数时都使用``但我想以中缀形式使用它,那该怎么办 method1 :: Int -> Int -> Int method1 a b = a + b main = print $ 1 method1 2 简而言之,你不能。如果b可能是中缀,那么想象一下a b c的可怕歧义
method1 :: Int -> Int -> Int
method1 a b = a + b
main = print $ 1 `method1` 2
如果我不想每次调用函数时都使用``但我想以中缀形式使用它,那该怎么办
method1 :: Int -> Int -> Int
method1 a b = a + b
main = print $ 1 method1 2
简而言之,你不能。如果
b
可能是中缀,那么想象一下a b c
的可怕歧义。但是您可以定义一个操作符来为您执行此操作。任何一个都可以
a |+| b = method1
(|+|) a b = method1 a b
(|+|) = method1
然后
haskell中缀运算符的允许字符是有限的,请从中选择
:|!@#$%^&*-+./<>?\~
:|!@$%^&*-+./\~
一个常见的库lens有很多操作符,它们充当较长名称的同义词。这很常见。不过,请务必使用判断,否则您最终会得到比Haskell更多的perl:)对此有一个卑鄙的“解决方案”——使用CPP宏。例如:
{-# LANGUAGE CPP #-}
#define method1 `themethod`
module Main where
themethod x y = x + y
someValue = 3 method1 4
这将编译,在ghci中,
someValue
将等于7。但是请不要这样做…注意:以:
(冒号)开头的运算符实际上是中缀类型构造函数。也就是说,冒号是与大写字母等效的运算符。我个人觉得这是一个非常烦人的特性,但我喜欢Data.Sequence库,因此我已经学会了处理它。这是一个巧妙的方式:)尽管你需要定义一个同义词,以便你可以映射它和其他东西
{-# LANGUAGE CPP #-}
#define method1 `themethod`
module Main where
themethod x y = x + y
someValue = 3 method1 4