Skip to content

Instantly share code, notes, and snippets.

@oisdk
Created July 3, 2015 17:46
Show Gist options
  • Save oisdk/08b31dd70623595eabed to your computer and use it in GitHub Desktop.
Save oisdk/08b31dd70623595eabed to your computer and use it in GitHub Desktop.
private extension GeneratorType {
mutating func foldr<T>(initial: T, @noescape combine: (Element, T) -> T) -> T {
return next().map { combine($0, foldr(initial, combine: combine) ) } ?? initial
}
}
public extension SequenceType {
func foldr<T>(initial: T, @noescape combine: (Generator.Element, T) -> T) -> T {
var g = self.generate()
return g.foldr(initial, combine: combine)
}
func foldr(@noescape combine: (Generator.Element, Generator.Element) -> Generator.Element) -> Generator.Element? {
var g = self.generate()
return g.next().map { g.foldr($0, combine: combine) }
}
}
[1, 2, 3, 4].foldr(0, combine: +) // 10
[1, 2, 3, 4].foldr(+) // 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment