Skip to content

Instantly share code, notes, and snippets.

@gregomni
Created July 13, 2016 18:29
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 gregomni/ef3f717f546ad145e0ff6de73b942b76 to your computer and use it in GitHub Desktop.
Save gregomni/ef3f717f546ad145e0ff6de73b942b76 to your computer and use it in GitHub Desktop.
public func sequence<T>(first: T, next: (T) -> T?, while test: (T) -> Bool) -> UnfoldSequence<T, (T?, Bool)> {
return sequence(state: (first, true), next: { (state: inout (T?, Bool)) -> T? in
switch state {
case (let value?, true):
state.1 = false
if !test(value) {
state.0 = nil; return nil
}
return value
case (let value?, false):
let nextValue = next(value)
if let nextValue = nextValue where !test(nextValue) {
state.0 = nil; return nil
}
state.0 = nextValue
return nextValue
case (nil, _):
return nil
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment