Questions

Convert each function to CPS.

Parity

function parity(n) {
    if(n < 0) {
        throw new Error("no negative numbers!");
    }
    if(n % 2 == 0) {
        return true;
    } else {
        return false;
    }
}

Sum List

tail-recursive
function sum_list(ls) {
    return tail_sum_list(ls, 0);
}
 
function tail_sum_list(ls, acc) {
    if(ls.length == 0) {
        return acc;
    } else {
        return tail_sum_list(ls, ls.pop() + acc);
    }
}
non tail-recursive
function sum_list(ls) {
    if(ls.length == 0) {
        return 0;
    } else {
        return ls.pop() + sum_list(ls);
    }
}

Ascending

function ascending(ls, prev) {
    if(ls.length == 0) {
        return true;
    } else {
        if(ls[0] < prev) {
            return false;
        } else {
            return ascending(ls, ls.shift());
        }
    }
}

Answers

Parity

function parity(n, cc, thro) {
    if(n < 0) {
        thro(n);
    }
    if(n % 2 == 0) {
        cc(true);
    } else {
        cc(false);
    }
}

Tail-Recursive Sum List

function sum_list(ls, cc) {
    sum_list_tail(ls, 0, 0, cc);
}
 
function sum_list_tail(ls, ind, acc, cc) {
    if(ind >= ls.length) {
        cc(acc);
    } else {
        sum_list_tail(ls, ind + 1, ls[ind] + acc, cc);
    }
}

Sum List

function sum_list(ls, ind, cc) {
    if(ind >= ls.length) {
        cc(0);
    } else {
        sum_list(ls, ind + 1, v => cc(v + ls[ind--]));
    }
}

Ascending

function ascending(ls, ind, prev, cc) {
    if(ind >= ls.length) {
        cc(true);
    } else {
        if(ls[ind] < prev) {
            cc(false);
        } else {
            ascending(ls, ind + 1, ls[ind], cc);
        }
    }
}