function sequence(start, step) {
var x = 0;
return function () {
start = start || 0;
step = step || 1;
var y = start + (step * x)
x++;
return y;
}
}
var gen = sequence(1, 1);
function square(x) { return x * x };
function fmap(mixin, fn) {
return function() {
return mixin(fn.apply(null, arguments));
}
}
var squareGen = fmap(square, gen);
console.log(squareGen()); // 1
console.log(squareGen()); // 4
console.log(squareGen()); // 9
console.log(squareGen()); // 16
function add(a, b) {
return a + b;
}
var squareAdd = fmap(square, add);
console.log(squareAdd(2, 3)); // 25 = (2 + 3) ^ 2
console.log(squareAdd(5, 7)); // 144 = (5 + 7) ^ 2
ZnVuY3Rpb24gc2VxdWVuY2Uoc3RhcnQsIHN0ZXApIHsKCXZhciB4ID0gMDsKCXJldHVybiBmdW5jdGlvbiAoKSB7CgkJc3RhcnQgPSBzdGFydCB8fCAwOwoJCXN0ZXAgPSBzdGVwIHx8IDE7CgkJdmFyIHkgPSBzdGFydCArIChzdGVwICogeCkKCQl4Kys7CgkJcmV0dXJuIHk7Cgl9Cn0KCgp2YXIgZ2VuID0gc2VxdWVuY2UoMSwgMSk7CgoKZnVuY3Rpb24gc3F1YXJlKHgpIHsgcmV0dXJuIHggKiB4IH07CgoKZnVuY3Rpb24gZm1hcChtaXhpbiwgZm4pIHsKCXJldHVybiBmdW5jdGlvbigpIHsKCQlyZXR1cm4gbWl4aW4oZm4uYXBwbHkobnVsbCwgYXJndW1lbnRzKSk7Cgl9Cn0KCgoKdmFyIHNxdWFyZUdlbiA9IGZtYXAoc3F1YXJlLCBnZW4pOwoKY29uc29sZS5sb2coc3F1YXJlR2VuKCkpOyAvLyAxCmNvbnNvbGUubG9nKHNxdWFyZUdlbigpKTsgLy8gNApjb25zb2xlLmxvZyhzcXVhcmVHZW4oKSk7IC8vIDkKY29uc29sZS5sb2coc3F1YXJlR2VuKCkpOyAvLyAxNgoKCgpmdW5jdGlvbiBhZGQoYSwgYikgeyAKICAgIHJldHVybiBhICsgYjsgCn0KCgp2YXIgc3F1YXJlQWRkID0gZm1hcChzcXVhcmUsIGFkZCk7CmNvbnNvbGUubG9nKHNxdWFyZUFkZCgyLCAzKSk7IC8vIDI1ID0gKDIgKyAzKSBeIDIKY29uc29sZS5sb2coc3F1YXJlQWRkKDUsIDcpKTsgLy8gMTQ0ID0gKDUgKyA3KSBeIDI=