diff --git a/samples/hof.js b/samples/hof.js index f0e4401..823ece1 100644 --- a/samples/hof.js +++ b/samples/hof.js @@ -3,7 +3,8 @@ var map = require('../pattern') , zip_with = require('../pattern') , filtera = require('../pattern') , maybe = require('../pattern') - , _, f, ac, l, l1, l2, cb, errcb + , foldl = require('../pattern') + , _, f, ac, l, l1, l2, cb, errcb, z ; // error handling for conditional execution of functions @@ -11,7 +12,9 @@ maybe(Error, _, errcb, cb, function (err, data, errcb, cb) { errcb(err); }); maybe(_, _, errcb, cb, function(err, data, errcb, cb) { cb(data); }); // map -map(f, [], ac, cb, +// map _ [] = [] +// map f (x:xs) = f x : map f xs +map(_, [], ac, cb, function map_done(f, l, ac, cb) { return cb(ac); }); map(f, l, ac, cb, function map_catch_all(f, l, ac, cb) { @@ -31,7 +34,11 @@ mapa(f, l, ac, cb, }); // filter with async f -filtera(f, [], ac, cb, function filter_done(f, l, ac, cb) { +// filter _ [] = [] +// filter p (x:xs) +// | p x = x : filter p xs +// | otherwise = filter p xs +filtera(_, [], ac, cb, function filter_done(f, l, ac, cb) { return cb(null, ac); }); filtera(f, l, ac, cb, function filter_catch_all(f, l, ac, cb) { @@ -44,14 +51,26 @@ filtera(f, l, ac, cb, function filter_catch_all(f, l, ac, cb) { }); }); -// foldl +// foldl with async f, no errors possible +// foldl f z [] = z +// foldl f z (x:xs) = foldl f (f z x) xs +foldl(f, z, [], cb, function foldl_done(f, z, l, cb) { cb(z); }); +foldl(f, z, l, cb, function foldl_all(f, z, l, cb) { + f(z, l.shift(), function foldl_f_async(new_z) { + foldl(f, new_z, l, cb); + }); +}); -zip_with(f, [], l2, ac, cb, function emptyl1(f, l1, l2, ac, cb) { cb(ac); }); -zip_with(f, l1, [], ac, cb, function emptyl2(f, l1, l2, ac, cb) { cb(ac); }); +// zipWith _ [] _ = [] +// zipWith _ _ [] = [] +// zipWith f (x:xs) (y:ys) = f x y : zipWith' f xs ys +zip_with(_, [], _, ac, cb, function emptyl1(f, l1, l2, ac, cb) { cb(ac); }); +zip_with(_, _, [], ac, cb, function emptyl2(f, l1, l2, ac, cb) { cb(ac); }); zip_with(f, l1, l2, ac, cb, function all(f, l1, l2, ac, cb) { ac.push(f(l1.shift(), l2.shift())); zip_with(f, l1, l2, ac, cb); }); module.exports = - { map: map, map_async: mapa, zip_with: zip_with, filter_async: filtera }; \ No newline at end of file + { map: map, map_async: mapa, zip_with: zip_with, filter_async: filtera + , foldl: foldl }; \ No newline at end of file diff --git a/samples/reverse_list_with_reduce.test.js b/samples/reverse_list_with_reduce.test.js new file mode 100644 index 0000000..431b015 --- /dev/null +++ b/samples/reverse_list_with_reduce.test.js @@ -0,0 +1,10 @@ +/* [ 1, 2, 3, 4, 5 ] */ +var reduce = require('./hof').foldl; + +function id(z, x, cb) { + setTimeout( + function() {z.unshift(x); cb(z);}, Math.ceil(Math.random() * 100)); } + +function reserve (list, cb) { reduce(id, [], list, function(z){ cb(z); }); } + +reserve([5,4,3,2,1], function (list) { console.error(list); }); \ No newline at end of file