Last active
January 22, 2021 22:34
-
-
Save airspeedswift/83eee31e1d9e52fd5570 to your computer and use it in GitHub Desktop.
Removing duplicates
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
// removes all but first occurrence from a sequence, returning an array. | |
// requires elements to be hashable, not just equatable, but the alternative | |
// of using contains is very inefficient | |
// alternatively, could require comparable, sort, and remove adjacent dupes | |
func uniq<S: SequenceType, E: Hashable where E==S.Generator.Element>(seq: S) -> [E] { | |
var seen: [S.Generator.Element:Int] = [:] | |
return filter(seq) { !seen.updateValue(1, forKey: $0).hasValue } | |
} | |
// TODO: a version that takes a custom comparator function, say for lexicographic deduping | |
// give String an initializer of a sequence of characters. | |
// (I'm not missing an existing one am I?) | |
extension String { | |
init<S: SequenceType where S.Generator.Element == Character>(_ seq: S) { | |
self.init() | |
self.extend(seq) | |
} | |
} | |
// removeDuplicates returns a version of the String with | |
// all duplicates removed | |
extension String { | |
func removeDuplicates() -> String { | |
return String(uniq(self)) | |
} | |
} | |
let s = "hello, I must be going".removeDuplicates() | |
// => "helo, Imustbgin" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cool!