How to define an xor operator in Io

262 Views Asked by At

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

There are 1 best solutions below

1
On BEST ANSWER

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