import 'dart:io'; // Generates a stream of n fibonacci numbers, sleeping 1 second every iteration Stream Function() fibonnaciNumbers(int n) { final Stream Function() func = (() async* { var x = 0, y = 1; for (int i = 0; i <= n; i++) { yield x; sleep(new Duration(seconds: 1)); y += x; x = y - x; } }); return func; } // Filters a stream of integers with a function predicate determining to each of the elements in the stream. Stream Function() streamFilter(Stream stream, bool Function(int) f) { final Stream Function() func = (() async* { await for (var i in stream) { if (f(i)) { yield i; } } }); return func; } // Iterates over a stream, accumulatively applying a binary function to a stream of integers until the last // element and returns the accumulation. Stream Function() streamAccumulation( Stream stream, int Function(int, int) f, initial) { final Stream Function() func = (() async* { int a = initial; await for (var i in stream) { a = f(a, i); yield a; } }); return func; } Stream Function() generateNumbers(int n) { final Stream Function() func = (() async* { for (int i = 1; i <= n; i++) { await Future.delayed(const Duration(seconds: 1)); yield i; } }); return func; } // Given a list of lists, returns a list containing all the non-null elements of each list into a single list List? flatten(List? aList) { if (aList == null) return null; return aList .where((i) => i != null) .expand((i) => i!) .where((i) => i != null) .toList(); } // Generates a nested list where each element's index i is in a sublist of depth i+1. // For example, deepen([1,2,3]) => [1, [2, [3]]] List? deepen(List? aList) { if (aList == null) return null; return aList.reversed .fold([], (a, x) => (a != null && a.isEmpty) ? [x] : [x, a]); } void main(List arguments) async { print('flattening [[0,1], [2]] yields ${flatten([ [0, 1], [2] ])}'); print('flattening [[0,1], [2], null] yields ${flatten([ [0, 1], [2], null ])}'); print('flattening [[0,1, null], [2]] yields ${flatten([ [0, 1, null], [2] ])}'); print('flattening null yields ${flatten(null)}'); print('flattening [null] yields ${flatten([null])}'); print('deepening [0,1,2] yields ${deepen([0, 1, 2])}'); print('deepening [0,null,2] yields ${deepen([0, null, 2])}'); print('deepening [0] yields ${deepen([0])}'); print('deepening [] yields ${deepen([])}'); print('deepening null yields ${deepen(null)}'); await for (final number in fibonnaciNumbers(7)()) { print('fibonnaci number is ${number}'); } await for (final number in streamFilter(generateNumbers(10)(), ((a) { return a % 2 == 0; }))()) { print('filtered number is $number'); } await for (final number in streamAccumulation(generateNumbers(10)(), ((a, b) { return a + b; }), 0)()) { print('cumulative number is $number.'); } }