Skip to content

Instantly share code, notes, and snippets.

@jarsen
Created December 12, 2014 20:49
Show Gist options
  • Save jarsen/b741462a051fcd9b8a86 to your computer and use it in GitHub Desktop.
Save jarsen/b741462a051fcd9b8a86 to your computer and use it in GitHub Desktop.
Functional Swift — Counting Frequencies
func update<K,V>(var dictionary: [K:V], key: K, value: V) -> [K:V] {
dictionary[key] = value
return dictionary
}
func increment<T>(dictionary: [T:Int], key: T) -> [T:Int] {
return update(dictionary, key, map(dictionary[key]) {$0 + 1} ?? 1)
}
func histogram<T>(var s: [T]) -> [T:Int] {
return reduce(s, [T:Int](), increment)
}
let foo = histogram([1,2,3,1,4,1,1,2,3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment