如何在Haskell中创建运算符?

时间:2012-02-20 05:08:44

标签: haskell-platform haskell haskelldb

创建一个三元逻辑表,我想为我称之为<=>的运算符创建自己的函数。

所以,例如,我想这样做,但那是不对的。这样做的正确方法是什么?

data Ternary = T | F | M
deriving (Eq,  Show, Ord)

<=> :: Ternary -> Ternary -> Ternary
<=> T F = F
<=> T T = T
<=> T M = M
<=> F F = T
<=> F T = F
<=> F M = M
<=> M F = M
<=> M T = M
<=> M M = T

4 个答案:

答案 0 :(得分:42)

只需在运营商周围添加括号:

(<=>) :: Ternary -> Ternary -> Ternary
(<=>) T F = F
(<=>) T T = T
(<=>) T M = M
(<=>) F F = T
(<=>) F T = F
(<=>) F M = M
(<=>) M F = M
(<=>) M T = M
(<=>) M M = T

这将它从中缀形式转换为前缀形式。或者,您可以在定义中使用中缀:

(<=>) :: Ternary -> Ternary -> Ternary
T <=> F = F
T <=> T = T
T <=> M = M
F <=> F = T
F <=> T = F
F <=> M = M
M <=> F = M
M <=> T = M
M <=> M = T

答案 1 :(得分:10)

带符号的函数名与不带符号的函数名不同:

-- Works:
(<^>) :: Int -> Int -> Int
a <^> b = a + b

-- Doesn't work:
{-
<^> :: Int -> Int -> Int
<^> a b = a + b
-}

-- Works:
letters :: Int -> Int -> Int
letters a b = a + b

-- Doesn't work:
{-
(letters) :: Int -> Int -> Int
a letters b = a + b
-}

我保证,Haskell非常值得学习复杂的规则。

答案 2 :(得分:1)

您可以按如下方式简化(按行)定义:

(<=>) :: Ternary -> Ternary -> Ternary
T <=> T = T
F <=> F = T
M <=> M = T
M <=> _ = M
_ <=> M = M
_ <=> _ = F

答案 3 :(得分:0)

由于您有EqOrd,因此您可以执行以下操作:

data Ternary = T | F | M
deriving (Eq, Show, Ord)

(<=>) :: Ternary -> Ternary -> Ternary
x <=> y = if x == y then T else max x y

如果您碰巧将其更改为M <=> M == M,那么您可以执行以下操作:

data Ternary = M | T | F
deriving (Eq, Show, Ord, Enum)

(<=>) :: Ternary -> Ternary -> Ternary
x <=> y = fromEnum $ rem (toEnum x * toEnum y) 3