Created
December 11, 2013 21:43
-
-
Save davidbalbert/7919022 to your computer and use it in GitHub Desktop.
Three implementations of `map` in continuation passing style.
This file contains hidden or 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
(function () { | |
"use strict"; | |
var first = function (arr, c) { | |
c(arr[0]); | |
}; | |
var rest = function (arr, c) { | |
c(arr.slice(1)); | |
}; | |
var append = function (arr, el, c) { | |
c(arr.concat([el])); | |
} | |
var map1 = function (arr, f, c) { | |
var helper = function (arr, newArr, f, c) { | |
if (arr.length == 0) { | |
c(newArr); | |
} else { | |
first(arr, function (oldFirst) { | |
rest(arr, function (r) { | |
f(oldFirst, function (newFirst) { | |
append(newArr, newFirst, function (newArr) { | |
helper(r, newArr, f, c); | |
}); | |
}); | |
}); | |
}); | |
} | |
} | |
helper(arr, [], f, c); | |
}; | |
var prepend = function (el, arr, c) { | |
c([el].concat(arr)); | |
} | |
var map2 = function (arr, f, c) { | |
if (arr.length == 0) { | |
c([]); | |
} else { | |
rest(arr, function (r) { | |
map2(r, f, function(newArr) { | |
first(arr, function (el) { | |
f(el, function (newEl) { | |
prepend(newEl, newArr, function (newArr) { | |
c(newArr); | |
}); | |
}); | |
}); | |
}); | |
}); | |
} | |
}; | |
var deCons = function (arr, c) { | |
first(arr, function (first) { | |
rest(arr, function (rest) { | |
c(first, rest); | |
}); | |
}); | |
}; | |
var map3 = function (arr, f, c) { | |
if (arr.length == 0) { | |
c([]); | |
} else { | |
deCons(arr, function (first, rest) { | |
map3(rest, f, function (newArr) { | |
f(first, function (el) { | |
prepend(el, newArr, function (newArr) { | |
c(newArr); | |
}); | |
}); | |
}); | |
}); | |
} | |
}; | |
var inc = function (i, c) { | |
c(i + 1); | |
}; | |
var arr = [1,2,3,4,5]; | |
map1(arr, inc, function (res) { console.log(res); }); | |
map2(arr, inc, function (res) { console.log(res); }); | |
map3(arr, inc, function (res) { console.log(res); }); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment