Created
March 15, 2021 12:23
-
-
Save MariaMelnik/5e483d1cc029c2b455e56579181b7e6c to your computer and use it in GitHub Desktop.
dart: lazy fibonacci generator
This file contains hidden or 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
void main() { | |
final fib = fibStream(); | |
print(fib.take(10)); | |
} | |
Iterable<int> fibStream() sync* { | |
final firstIt = fromList([0]).followedBy(fibStream()); | |
final secondIt = fromList([0,1]).followedBy(fibStream());; | |
yield* zipWith(sumInt, firstIt, secondIt); | |
} | |
Iterable<T> zipWith<T,S>(T Function(S a, S b) f, Iterable<S> a, Iterable<S> b) sync* { | |
if (a.isNotEmpty && b.isNotEmpty) { | |
final firstVal = f.call(a.first, b.first); | |
final firstIt = fromList<T>([firstVal]); | |
yield* firstIt.followedBy(zipWith<T,S>(f, tail(a), tail(b))); | |
} | |
} | |
Iterable<int> limitlessIt (int start) sync* { | |
final curIt = Iterable<int>.generate(1, (_) => start); | |
yield* curIt.followedBy(limitlessIt(start+1)); | |
} | |
Iterable<T> fromList<T>(List<T> list) { | |
return Iterable<T>.generate(list.length, (i) => list[i]); | |
} | |
Iterable<T> tail<T>(Iterable<T> it) { | |
return it.skip(1); | |
} | |
int sumInt(int a, int b) => a + b; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment