如何在Io中定义Xor运算符 [英] How to define an xor operator in Io
问题描述
我正在研究(香肠王").我已经直接从书中复制了代码,但是它不起作用.
I'm working through Chapter 3, Day to of Seven Languages in Seven Weeks ("The Sausage King"). I've copied the code straight out of the book, but it's not working.
Io 20110905
将新的运算符添加到OperatorTable.
Add a new operator to the OperatorTable.
Io> OperatorTable addOperator("xor", 11)
==> OperatorTable_0x336040:
Operators
0 ? @ @@
1 **
2 % * /
3 + -
4 << >>
5 < <= > >=
6 != ==
7 &
8 ^
9 |
10 && and
11 or xor ||
12 ..
13 %= &= *= += -= /= <<= >>= ^= |=
14 return
Assign Operators
::= newSlot
:= setSlot
= updateSlot
To add a new operator: OperatorTable addOperator("+", 4) and implement the + message.
To add a new assign operator: OperatorTable addAssignOperator("=", "updateSlot") and implement the updateSlot message.
输出确认已将其添加到插槽11中.现在让我们确保true尚未定义xor方法.
The output confirms that it was added in slot 11. Now let's make sure true doesn't already have an xor method defined.
Io> true slotNames
==> list(not, asString, asSimpleString, type, else, ifFalse, ifTrue, then, or, elseif, clone, justSerialized)
不是.因此,让我们创建它.
It does not. So let's create it.
Io> true xor := method(bool if(bool, false, true))
==> method(
bool if(bool, false, true)
)
还有一个为假.
Io> false xor := method(bool if(bool, true, false))
==> method(
bool if(bool, true, false)
)
现在检查是否已添加xor运算符.
Now check that the xor operator was added.
Io> true slotNames
==> list(not, asString, asSimpleString, type, else, xor, ifFalse, ifTrue, then, or, elseif, clone, justSerialized)
太好了.我们可以使用吗? (同样,这段代码直接来自本书.)
Great. Can we use it? (Again, this code is straight from the book.)
Io> true xor true
Exception: true does not respond to 'bool'
---------
true bool Command Line 1
true xor Command Line 1
不.而且我不确定不响应'布尔'"是什么意思.
No. And I'm not sure what "does not respond to 'bool'" means.
推荐答案
您忘记了逗号,并定义了一个无参数方法,其第一个消息为bool
-true
(在其上被调用)不知道有什么关系.你想做的是
You've forgot the comma and defined a parameterless method whose first message is bool
- which true
(on which it is called) does not know anything to do with. What you wanted to do was
true xor := method(bool, if(bool, false, true))
// ^
// or much simpler:
false xor := true xor := method(bool, self != bool)
// or maybe even
false xor := true xor := getSlot("!=")
// or, so that it works on all values:
Object xor := getSlot("!=")
这篇关于如何在Io中定义Xor运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!