如何在Io中定义xor运算符

Pat*_*ney 1 xor iolanguage

我正在完成第七章,即七周语言中七种语言("香肠之王").我直接从书中复制了代码,但它没有用.

Io 20110905
Run Code Online (Sandbox Code Playgroud)

将新运算符添加到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.
Run Code Online (Sandbox Code Playgroud)

输出确认它已添加到插槽11中.现在让我们确保true尚未定义xor方法.

Io> true slotNames
==> list(not, asString, asSimpleString, type, else, ifFalse, ifTrue, then, or, elseif, clone, justSerialized)
Run Code Online (Sandbox Code Playgroud)

它不是.所以让我们创造它.

Io> true xor := method(bool if(bool, false, true))
==> method(
    bool if(bool, false, true)
)
Run Code Online (Sandbox Code Playgroud)

还有一个是虚假的.

Io> false xor := method(bool if(bool, true, false))
==> method(
    bool if(bool, true, false)
)
Run Code Online (Sandbox Code Playgroud)

现在检查是否添加了xor运算符.

Io> true slotNames
==> list(not, asString, asSimpleString, type, else, xor, ifFalse, ifTrue, then, or, elseif, clone, justSerialized)
Run Code Online (Sandbox Code Playgroud)

大.我们可以用吗?(同样,这段代码直接来自本书.)

Io> true xor true

  Exception: true does not respond to 'bool'
  ---------
  true bool                            Command Line 1
  true xor                             Command Line 1
Run Code Online (Sandbox Code Playgroud)

不,我不确定"对'bool'没有回应"的意思.

Ber*_*rgi 6

你已经忘记了逗号并定义了一个无参数的方法,它的第一条消息是bool- 它true(在它上面被调用)与之无关.你想做的是

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("!=")
Run Code Online (Sandbox Code Playgroud)