I've written this extension to SequenceType
to mimic Python's collections.Counter
.
let input = [
"a", "a", "a", "a", "a",
"b", "b", "b", "b",
"c", "c", "c",
"d", "d",
"e"
]
let counts = input.countRepetitions()
print(counts) //expected result: ["a": 5 , "b" : 4, "c" : 3, "d" : 2, "e" : 1]
Here's the code:
extension SequenceType where Self.Generator.Element : Hashable {
func countRepetitions() -> [Self.Generator.Element : Int] {
return self.reduce([Self.Generator.Element : Int]()) { dict, element in
dict[key: element] = (dict[element] ?? 0) + 1
}
}
}
I get the following error:
Playground execution failed: OS X.playground:26:22: error: type of expression is ambiguous without more context
return self.reduce([Self.Generator.Element : Int]()) { dict, element in
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~