Created
August 2, 2015 20:25
-
-
Save sonsongithub/fde90049cda3c4a2d05c to your computer and use it in GitHub Desktop.
foldr and foldl in Swift2.0
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
extension CollectionType { | |
func foldr<B>(accm:B, f: (Self.Generator.Element, B) -> B) -> B { | |
var g = self.generate() | |
func next() -> B { | |
return g.next().flatMap {x in f(x, next())} ?? accm | |
} | |
return next() | |
} | |
func foldl<B>(accm:B, f: (Self.Generator.Element, B) -> B) -> B { | |
var result = accm | |
for temp in self { | |
result = f(temp, result) | |
} | |
return result | |
} | |
} | |
[10, 1, 3, 4, -4].foldr(1) { (acc, x) -> Int in | |
return acc + 2 * x | |
} | |
[10, 1, 3, 4, -4].foldl(1) { (acc, x) -> Int in | |
return acc + 2 * x | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment