Pony features two forms of equality: by structure and by identity.

Identity equality

Identity equality checks in Pony are done via the is keyword. is verifies that the two items are the same.

  1. if None is None then
  2. // TRUE!
  3. // There is only 1 None so the identity is the same
  4. end
  5. let a = Foo("hi")
  6. let b = Foo("hi")
  7. if a is b then
  8. // NOPE. THIS IS FALSE
  9. end
  10. let c = a
  11. if a is c then
  12. // YUP! TRUE!
  13. end

Structural equality

Structural equality checking in Pony is done via the infix operator ==. It verifies that two items have the same value. If the identity of the items being compared is the same, then by definition they have the same value.

You can define how structural equality is checked on your object by implementing fun eq(that: box->Foo): Bool. Remember, since == is an infix operator, eq must be defined on the left operand, and the right operand must be of type Foo.

  1. class Foo
  2. let _a: String
  3. new create(a: String) =>
  4. _a = a
  5. fun eq(that: box->Foo): Bool =>
  6. this._a == that._a
  7. actor Main
  8. new create(e: Env) =>
  9. let a = Foo("hi")
  10. let b = Foo("bye")
  11. let c = Foo("hi")
  12. if a == b then
  13. // won't print
  14. e.out.print("1")
  15. end
  16. if a == c then
  17. // will print
  18. e.out.print("2")
  19. end
  20. if a is c then
  21. // won't print
  22. e.out.print("3")
  23. end

If you don’t define your own eq, you will inherit the default implementation that defines equal by value as being the same as by identity.

  1. interface Equatable[A: Equatable[A] #read]
  2. fun eq(that: box->A): Bool => this is that
  3. fun ne(that: box->A): Bool => not eq(that)

Primitives and equality

As you might remember from Chapter 2, primitives are the same as classes except for two important differences:

  • A primitive has no fields.
  • There is only one instance of a user-defined primitive.

This means, that every primitive of a given type, is always structurally equal and equal based on identity. So, for example, None is always None.

  1. if None is None then
  2. // this is always true
  3. end
  4. if None == None then
  5. // this is also always true
  6. end