Skip to content

Instantly share code, notes, and snippets.

@oisdk

oisdk/fib.swift

Last active Aug 29, 2015
Embed
What would you like to do?
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
You can’t perform that action at this time.