Last active
August 29, 2015 14:24
-
-
Save oisdk/71f8ee43080eae8dcd6d to your computer and use it in GitHub Desktop.
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
public class SelectGenerator<T> : GeneratorType { | |
private let (head, tail): (T, [T]) | |
private var first: Bool = true | |
private var gen: SelectGenerator<T>? | |
public func next() -> (T, [T])? { | |
return first ? { | |
first = false | |
if !tail.isEmpty { gen = SelectGenerator(vals: tail) } | |
return (head, tail) | |
}() : gen?.next().map { ($0, [head] + $1) } | |
} | |
public init(var vals: [T]) { | |
self.head = vals.removeAtIndex(0) | |
self.tail = vals | |
} | |
} | |
var g = SelectGenerator(vals: [1, 2, 3, 4]) | |
g.next() // (1, [2, 3, 4]) | |
g.next() // (2, [1, 3, 4]) | |
g.next() // (3, [1, 2, 4]) | |
g.next() // (4, [1, 2, 3]) | |
g.next() // nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment