Skip to content

Instantly share code, notes, and snippets.

@VoQn
Created October 19, 2011 04:50
Show Gist options
  • Save VoQn/1297497 to your computer and use it in GitHub Desktop.
Save VoQn/1297497 to your computer and use it in GitHub Desktop.
Functional programing for Dart
// Functional list programinng Factory
class FF {
static fold(func(x, r), [init, Iterable it]) =>
init === null ?
(init, [Iterable it]) => FF.fold(func, init, it) :
it === null ?
(Iterable it) => FF.fold(func, init, it) :
(){
var result = init;
for (var i in it) result = func(i, result);
return result;
}();
static void each(func(x), [Iterable it]){
if (it === null) {
return (Iterable it) => FF.each(func, it);
}
for (var i in it) func(i);
}
static Iterable map(func(v), [Iterable it]) =>
it === null ?
(Iterable it) => FF.map(func, it) :
FF.fold((x, r){
r.add(func(x));
return r;
}, [], it);
static Iterable filter(bool func(v), [Iterable it]) =>
it === null ?
(Iterable it) => FF.filter(func, it) :
FF.fold((x, r){
if (func(x)) r.add(x);
return r;
}, [], it);
static Iterable list(next(x), [init, bool test(x)]) =>
init === null ?
(init, [bool test(x)]) => FF.list(next, init, test) :
test === null ?
(bool test(x)) => FF.list(next, init, test) :
(){
var result = [];
for (var i = init; test(i); i = next(i)) result.add(i);
return result;
}();
static id(x) => x;
static compose(Iterable<Function> fs) =>
FF.fold((g, f) =>
(x) => f(g(x)), FF.id, fs);
}
main(){
String fizzbuzz(int n) =>
n % 15 < 1 ? 'FizzBuzz' :
n % 5 < 1 ? 'Buzz' :
n % 3 < 1 ? 'Fizz' :
'$n';
int fibonacci(int n) {
int iter(int c, [int a = 1, int b = 0]) =>
c < 2 ? a : iter(c - 1, a + b, a);
return iter(n);
}
(i, l){
FF.each(
FF.compose([print, fizzbuzz, fibonacci]),
FF.list((x) => x + 1, i, (x) => x <= l));
}(1, 1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment