Skip to content

Instantly share code, notes, and snippets.

@pyrtsa
Created February 24, 2015 07:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pyrtsa/4df24d4a141f3343d574 to your computer and use it in GitHub Desktop.
Save pyrtsa/4df24d4a141f3343d574 to your computer and use it in GitHub Desktop.
foldr in Swift
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".
@volodg
Copy link

volodg commented Dec 6, 2015

Your implementation cause a leak, here fixed swift 2 foldr

extension CollectionType {

public func foldr<B>(zero: B, f: (Generator.Element, () -> B) -> B) -> B {

    var g = generate()
    var next: (() -> B)! = {zero}

    next = { return g.next().map {x in f(x, next)} ?? zero }
    let result = next()
    next = nil
    return result
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment