TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Solving balanced parentheses problem using Dart's type system

5 pointsby shilangyuabout 2 years ago

1 comment

slavapestovabout 2 years ago
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> &lt;a, b where ab=e&gt; </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&lt;T&gt;(_: T.Type, _: T.Type) {} func f&lt;T: P&gt;(_: T) { sameType(T.A.A.A.B.A.B.B.B.self, T.self) &#x2F;&#x2F; type checks sameType(T.B.B.A.self, T.self) &#x2F;&#x2F; 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&#x27;t tried it but it should work).
评论 #35788332 未加载