如何在Haskell上创建独占或使用它?
我正在尝试创建一个函数,该函数根据 3 边长度的输入来判断三角形的类型。
triangle a b c
|a+b<c = error "Not a triangle"
|a==b ... a==c ... c==b = isosceles triangle
|a==b && b==c = "equilateral triangle"
|otherwise = "scalene triangle"
由于等腰三角形只有两条相等的边,我不能使用“||”。
我创建了该函数,但我不知道如何将其用作运算符。
exclusiveOR a b = (a||b)&& not(a&&b)
回答
您可以使用它前缀,也可以将其括在反引号中以使其成为中缀:
| exclusiveOR foo bar = ...
| foo `exclusiveOR` bar = ...
顺便说一下,这个函数有一个现有的短名称。
| foo /= bar = ...
- @Heil You almost certainly have seen that function before at some point. It means "not equal to" (sometimes written as `!=` or as `≠` elsewhere). You are just applying it to booleans in this specific scenario. Note a xor b is precisely true when a and b are not the same and false when a and b are the same.
回答
只需切换案例的顺序即可。a==b && b==c先检查;如果失败,则检查a==b || a==c || c==b,如果成功,则三角形必须是等腰三角形(因为您已经消除了等边情况)。