Created
July 3, 2015 17:46
-
-
Save oisdk/08b31dd70623595eabed to your computer and use it in GitHub Desktop.
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
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