Skip to content

Instantly share code, notes, and snippets.

@pyrtsa
Created February 24, 2015 07:55

Revisions

  1. pyrtsa created this gist Feb 24, 2015.
    12 changes: 12 additions & 0 deletions foldr.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    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".