Balanced parentheses can also be encoded in Swift or Rust.<p>Another way to think about the problem is that we can define a finitely-presented monoid, called the bicyclic monoid, with identity element <i>e</i>, two generators <i>a</i> and <i>b</i>, and the relation <i>ab=e</i>:<p><pre><code> <a, b where ab=e>
</code></pre>
Then, ( corresponds to <i>a</i> and ) corresponds to <i>b</i>, and a string like <i>aaababbb</i> is balanced if it is equivalent to <i>e</i> via the identity element.<p>A finitely-presented monoid corresponds directly to a protocol declaration in Swift:<p><pre><code> protocol P {
associatedtype A: P
associatedtype B: P where A.B == Self
}
</code></pre>
Now you can declare a function which is generic over a type conforming to `P`:<p><pre><code> sameType<T>(_: T.Type, _: T.Type) {}
func f<T: P>(_: T) {
sameType(T.A.A.A.B.A.B.B.B.self, T.self) // type checks
sameType(T.B.B.A.self, T.self) // error, not balanced
}
</code></pre>
The call to sameType() will type check if and only if both type arguments are equivalent.<p>In Rust you can similarly define a trait with two associated types and a where clause (I haven't tried it but it should work).