-
Notifications
You must be signed in to change notification settings - Fork 71
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #127 from matthewleon/nonempty
NonEmpty arrays
- Loading branch information
Showing
5 changed files
with
860 additions
and
1 deletion.
There are no files selected for viewing
This file contains 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
This file contains 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
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); | ||
}; | ||
}; | ||
}; | ||
}; | ||
}(); |
Oops, something went wrong.