Skip to content

Instantly share code, notes, and snippets.

@oisdk
Last active August 29, 2015 14:21
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/79095c4a7cdcf7587464 to your computer and use it in GitHub Desktop.
Save oisdk/79095c4a7cdcf7587464 to your computer and use it in GitHub Desktop.
var (a, b) = (1, 0)
var fibs = lazy(
GeneratorOf<Int> {
(b, a) = (a, b + a)
return b
}
)
extension LazySequence {
func takeWhile(condition: S.Generator.Element -> Bool)
-> LazySequence<GeneratorOf<S.Generator.Element>> {
var gen = self.generate()
return lazy( GeneratorOf{ gen.next().flatMap{ condition($0) ? $0 : nil }})
}
func reduce<U>(initial: U, combine: (U, S.Generator.Element) -> U) -> U {
var accu = initial
for element in self { accu = combine(accu, element) }
return accu
}
}
fibs
.filter{$0 % 2 == 0}
.takeWhile{$0 < 100}
.reduce(0, combine: +)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment