Skip to content

Instantly share code, notes, and snippets.

@oisdk
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oisdk/71f8ee43080eae8dcd6d to your computer and use it in GitHub Desktop.
Save oisdk/71f8ee43080eae8dcd6d to your computer and use it in GitHub Desktop.
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