Last active
January 19, 2018 23:34
-
-
Save iosdevzone/55a1c742efb603cb7d57c8dd5c41887f to your computer and use it in GitHub Desktop.
RecursiveSubSequence is a protocol I've found useful.
This file contains 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
protocol RecursiveSubSequence: Sequence where SubSequence: RecursiveSubSequence { } | |
extension String: RecursiveSubSequence { } | |
extension Substring: RecursiveSubSequence { } | |
extension Array: RecursiveSubSequence {} | |
extension ArraySlice: RecursiveSubSequence {} | |
func process<T>(_ value: T) -> T { return value } | |
func count<S: RecursiveSubSequence>(_ s: S) -> Int { | |
guard let head = (s.first { _ in true }) else { return 0 } | |
process(head) // supress compiler warning | |
let tail = s.dropFirst() | |
return count(tail) + 1 | |
} | |
count("aa") // -> 2 | |
count([1,2,3]) // -> 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment