Skip to content

Instantly share code, notes, and snippets.

@bcobb
Created February 23, 2018 15:44
Show Gist options
  • Save bcobb/3c508342aeb3ca4e746c1d941044278c to your computer and use it in GitHub Desktop.
Save bcobb/3c508342aeb3ca4e746c1d941044278c to your computer and use it in GitHub Desktop.
function emptyList() {
return function(which) {
return which(undefined, emptyList(), true);
};
}
function prepend(head, tail) {
return function(which) {
return which(head, tail, false);
};
}
function head(list) {
return list(function(head, _tail, _isEmpty) {
return head;
});
}
function tail(list) {
return list(function(_head, tail, _isEmpty) {
return tail;
});
}
function isEmpty(list) {
return list(function(_head, _tail, isEmpty) {
return isEmpty;
});
}
function map(mapping, list) {
if (isEmpty(list)) {
return list;
} else {
return prepend(
mapping(head(list)),
map(mapping, tail(list))
);
}
}
function reduce(reduction, initialValue, list) {
if (isEmpty(list)) {
return initialValue;
} else {
return reduce(
reduction,
reduction(initialValue, head(list)),
tail(list)
);
}
}
var example = prepend(
1,
prepend(2, prepend(3, emptyList()))
);
head(example); // => 1
head(
map(function(i) {
return i + 1;
}, example)
); // => 2
reduce(
function(sum, i) {
return sum + i;
},
0,
example
); // => 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment