Created
February 24, 2015 07:55
-
-
Save pyrtsa/4df24d4a141f3343d574 to your computer and use it in GitHub Desktop.
foldr in Swift
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
func foldr<A : SequenceType, B>(xs: A, y: B, f: (A.Generator.Element, () -> B) -> B) -> B { | |
var g = xs.generate() | |
var next: () -> B = {y} | |
next = { return g.next().map {x in f(x, next)} ?? y } | |
return next() | |
} | |
foldr([1, 2, 3, -4, -5, 6], "") {a, b in | |
println(a) | |
return a < 0 ? toString(a) : b() | |
} | |
// Prints the lines 1, 2, 3, -4, and then returns "-4". |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your implementation cause a leak, here fixed swift 2 foldr
extension CollectionType {
}