PEP 584: Survey of other languages (operator overload)

I surveyed other popular languages having operator overload. This topic is not for voting PEP 584. Just for gathering one of information for making a decision.

I used here instead of ML to update this post by reply.

C++

C++ doesn’t use operator overload for containers much.

  • No operator for concatenate vectors
  • No operator for union of set
  • No operator for merging maps

C#

Like C++, C# doesn’t use operator overload for containers.

Ruby

Swift

Rust

I’m not familiar with Rust so I’m not sure. But it seems implementing traits in core::ops means overloading operator.

Scala

  • ++ for concat Seq: ref
  • | for union of Set: ref
  • ++ for adding elements from iterator into Set: ref
  • ++ for merging DefaultMap: ref
  • + for adding one or some key: value pairs to DefaultMap (e.g. Similar to Python’s dict.update(key=val, key2=val2) form). ref

Note:

  • Scala uses + for adding one or some elements, and ++ for adding elements from iterator.

Kotlin

Note:

  • Kotlin can overload + but |. So it didn’t mean Kotlin chose + over |.
  • - of HashMap takes key or iterator of keys, not Map.
2 Likes

Rust’s API is heavily iterator based, so it’s something like a.into_iter().chain(b).collect(). There’s no overloaded operator for this, but the reason is more complicated than a design decision due to memory management.

Ruby hashes have no operators for this, but many methods (versions with ! mutate in-place):

pry(main)> a = {1 => 10}
=> {1=>10}
pry(main)> b = {2 => 20}
=> {2=>20}

# Merging:
pry(main)> a.merge(b)
=> {1=>10, 2=>20}
pry(main)> a
=> {1=>10}
pry(main)> a.merge!(b)  # like Python's .update()
=> {1=>10, 2=>20}
pry(main)> a
=> {1=>10, 2=>20}

# Subset with given keys:
pry(main)> a.slice(1)
=> {1=>10}
pry(main)> a.slice(2)
=> {2=>20}
pry(main)> a
=> {1=>10, 2=>20}
pry(main)> a.slice!(1)  # ActiveSupport extension
=> {2=>20}
pry(main)> a
=> {1=>10}

# Drop given keys
pry(main)> a.except(1)  # ActiveSupport extension
=> {2=>20}
pry(main)> a
=> {1=>10, 2=>20}
pry(main)> a.except!(1)  # ActiveSupport extension
=> {2=>20}
pry(main)> a
=> {2=>20}

It’s also interesting that Ruby arrays use + for concatenation, and at the same time |, & and - for set operations:

pry(main)> [1, 2] + [3, 1]
=> [1, 2, 3, 1]
pry(main)> [1, 2] | [3, 1]
=> [1, 2, 3]
pry(main)> [1, 2] - [3, 1]
=> [2]
pry(main)> [1, 2] & [3, 1]
=> [1]

(It also has a Set class supporting same operations except both + and | do union.)