How to define an xor operator in Io

偶尔善良 提交于 2019-12-11 12:26:50

问题


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

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.

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)
)

And one for false as well.

Io> false xor := method(bool if(bool, true, false))
==> method(
    bool if(bool, true, false)
)

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.


回答1:


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("!=")


来源:https://stackoverflow.com/questions/27445142/how-to-define-an-xor-operator-in-io

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!