Balanced parentheses can also be encoded in Swift or Rust.
Another way to think about the problem is that we can define a finitely-presented monoid, called the bicyclic monoid, with identity element e, two generators a and b, and the relation ab=e:
<a, b where ab=e>
Then, ( corresponds to a and ) corresponds to b, and a string like aaababbb is balanced if it is equivalent to e via the identity element.
A finitely-presented monoid corresponds directly to a protocol declaration in Swift:
protocol P {
associatedtype A: P
associatedtype B: P where A.B == Self
}
Now you can declare a function which is generic over a type conforming to `P`:
Another way to think about the problem is that we can define a finitely-presented monoid, called the bicyclic monoid, with identity element e, two generators a and b, and the relation ab=e:
Then, ( corresponds to a and ) corresponds to b, and a string like aaababbb is balanced if it is equivalent to e via the identity element.A finitely-presented monoid corresponds directly to a protocol declaration in Swift:
Now you can declare a function which is generic over a type conforming to `P`: The call to sameType() will type check if and only if both type arguments are equivalent.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).