Last active
November 21, 2015 12:44
-
-
Save YusukeHosonuma/ebe5e55147ef99078f42 to your computer and use it in GitHub Desktop.
Three ways to implementation group() function.
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
import Foundation | |
extension SequenceType where Generator.Element : Equatable { | |
typealias E = Generator.Element | |
// use reduce() | |
func group() -> [[E]] { | |
let initial: [[E]] = [] | |
let grouped = self.reduce(initial) { (var acc, x) -> [[E]] in | |
if var lastGroup = acc.last where lastGroup.last == x { | |
acc.removeLast() | |
lastGroup.append(x) | |
acc.append(lastGroup) | |
} else { | |
acc.append([x]) | |
} | |
return acc | |
} | |
return grouped | |
} | |
// use forEach() | |
func group2() -> [[E]] { | |
var grouped: [[E]] = [] | |
self.forEach { (x) -> () in | |
if var lastGroup = grouped.last where lastGroup.last == x { | |
grouped.removeLast() | |
lastGroup.append(x) | |
grouped.append(lastGroup) | |
} else { | |
grouped.append([x]) | |
} | |
} | |
return grouped | |
} | |
// use for-in | |
func group3() -> [[E]] { | |
var grouped: [[E]] = [] | |
for x in self { | |
if var lastGroup = grouped.last where lastGroup.last == x { | |
grouped.removeLast() | |
lastGroup.append(x) | |
grouped.append(lastGroup) | |
} else { | |
grouped.append([x]) | |
} | |
} | |
return grouped | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment