Created
February 19, 2026 18:48
-
-
Save DanielCardonaRojas/c2d7ff8cf69cb3af473f417e132d8a7d to your computer and use it in GitHub Desktop.
Partition Sets into mutually exclusive subsets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @dynamicMemberLookup | |
| struct Partition<Element: CaseIterable & Hashable, Case: CaseIterable & Hashable> { | |
| private let subsets: [Case: Set<Element>] | |
| private let classify: (Element) -> Case | |
| init(by classify: @escaping (Element) -> Case) { | |
| self.classify = classify | |
| var subsets: [Case: Set<Element>] = Dictionary( | |
| uniqueKeysWithValues: Case.allCases.map { ($0, []) } | |
| ) | |
| for element in Element.allCases { | |
| subsets[classify(element)]!.insert(element) | |
| } | |
| self.subsets = subsets | |
| } | |
| subscript(_ case: Case) -> Set<Element> { | |
| subsets[`case`, default: []] | |
| } | |
| func classification(for element: Element) -> Case { | |
| classify(element) | |
| } | |
| } | |
| extension Partition where Case: RawRepresentable, Case.RawValue == String { | |
| subscript(dynamicMember member: String) -> Set<Element> { | |
| guard let key = Case(rawValue: member) else { | |
| return [] | |
| } | |
| return subsets[key, default: []] | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: