Skip to content

Instantly share code, notes, and snippets.

@sonsongithub
Created August 2, 2015 20:25
Show Gist options
  • Save sonsongithub/fde90049cda3c4a2d05c to your computer and use it in GitHub Desktop.
Save sonsongithub/fde90049cda3c4a2d05c to your computer and use it in GitHub Desktop.
foldr and foldl in Swift2.0
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