Skip to content

Instantly share code, notes, and snippets.

@pyrtsa
Last active December 28, 2015 19:40
Show Gist options
  • Save pyrtsa/d5d0d4b864d49d312ae5 to your computer and use it in GitHub Desktop.
Save pyrtsa/d5d0d4b864d49d312ae5 to your computer and use it in GitHub Desktop.
Semigroupy grouping magic in Swift
// What people often ask DefaultDict for, could be done with just one
// extension method for Optional.
extension Optional {
mutating func mappend(z: Wrapped, _ f: (Wrapped, Wrapped) -> Wrapped) {
self = map {x in f(x, z)} ?? z
}
}
// --- Examples ------------------------------------------------------------
let strings = ["foo", "bar", "xyzzy", "oh", "good", "bad", "great"]
var groups = [Int: [String]]()
for s in strings {
groups[s.characters.count].mappend([s], +)
}
print(groups) //=> [5: ["xyzzy", "great"], 2: ["oh"], 3: ["foo", "bar", "bad"], 4: ["good"]]
// ---
var counts = [Int: Int]()
for s in strings {
counts[s.characters.count].mappend(1, +)
}
print(counts) //=> [5: 2, 2: 1, 3: 3, 4: 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment