Skip to content

Commit

Permalink
Merge pull request #127 from matthewleon/nonempty
Browse files Browse the repository at this point in the history
NonEmpty arrays
  • Loading branch information
garyb authored Mar 10, 2018
2 parents ebcfcc3 + badad04 commit c87fdee
Show file tree
Hide file tree
Showing 5 changed files with 860 additions and 1 deletion.
2 changes: 1 addition & 1 deletion bower.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"package.json"
],
"dependencies": {
"purescript-foldable-traversable": "^3.0.0",
"purescript-foldable-traversable": "^3.3.0",
"purescript-nonempty": "^4.0.0",
"purescript-partial": "^1.2.0",
"purescript-st": "^3.0.0",
Expand Down
77 changes: 77 additions & 0 deletions src/Data/Array/NonEmpty.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
"use strict";

exports.fold1Impl = function (f) {
return function (xs) {
var acc = xs[0];
var len = xs.length;
for (var i = 1; i < len; i++) {
acc = f(acc)(xs[i]);
}
return acc;
};
};

exports.traverse1Impl = function () {
function Cont(fn) {
this.fn = fn;
}

var emptyList = {};

var ConsCell = function (head, tail) {
this.head = head;
this.tail = tail;
};

function finalCell(head) {
return new ConsCell(head, emptyList);
}

function consList(x) {
return function (xs) {
return new ConsCell(x, xs);
};
}

function listToArray(list) {
var arr = [];
var xs = list;
while (xs !== emptyList) {
arr.push(xs.head);
xs = xs.tail;
}
return arr;
}

return function (apply) {
return function (map) {
return function (f) {
var buildFrom = function (x, ys) {
return apply(map(consList)(f(x)))(ys);
};

var go = function (acc, currentLen, xs) {
if (currentLen === 0) {
return acc;
} else {
var last = xs[currentLen - 1];
return new Cont(function () {
var built = go(buildFrom(last, acc), currentLen - 1, xs);
return built;
});
}
};

return function (array) {
var acc = map(finalCell)(f(array[array.length - 1]));
var result = go(acc, array.length - 1, array);
while (result instanceof Cont) {
result = result.fn();
}

return map(listToArray)(result);
};
};
};
};
}();
Loading

0 comments on commit c87fdee

Please sign in to comment.