Created
July 13, 2016 18:29
-
-
Save gregomni/ef3f717f546ad145e0ff6de73b942b76 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 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