【问题标题】:How to define an xor operator in Io如何在 Io 中定义 xor 运算符
【发布时间】:2015-02-11 06:03:52
【问题描述】:

我正在完成Seven Languages in Seven Weeks(“香肠之王”)的第 3 章。我直接从书中复制了代码,但它不起作用。

Io 20110905

向 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 方法。

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

它没有。所以让我们创建它。

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 运算符。

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

太好了。我们可以使用它吗? (同样,这段代码直接来自书中。)

Io> true xor true

  Exception: true does not respond to 'bool'
  ---------
  true bool                            Command Line 1
  true xor                             Command Line 1

没有。而且我不确定“不响应'bool'”是什么意思。

【问题讨论】:

  • 你在那里使用的bool 是什么东西?

标签: xor iolanguage


【解决方案1】:

您忘记了逗号并定义了一个无参数方法,其第一条消息是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("!=")

【讨论】:

  • 感谢您的出色回答,不仅指出了错字,还教会了我一些东西!
猜你喜欢
  • 2016-10-17
  • 2015-05-01
  • 2023-03-03
  • 2013-04-20
  • 2012-09-12
  • 2017-07-13
  • 2011-08-24
  • 2011-07-21
  • 1970-01-01
相关资源
最近更新 更多