Fun with diagonalization

No more loops, embrace the future with recursive self-modifying code and diagonalization. In the following code snippet, we show how to replace loops like ‘while E do C’ with only ‘if’ and ‘eval’ statements:


// expects stmt == 'if(expr) { command }'
function Z(stmt) {
    start = stmt.indexOf('(')+1;
    end = stmt.indexOf(')');
    expr = stmt.substr(start, end-start);

    start = stmt.indexOf('{')+1;
    end = stmt.lastIndexOf('}');
    command = stmt.substr(start, end-start);

    out = 'if ('+expr+') {'+command+'; stmt=\'if('+expr+') {'+command+'}\'; eval(Z(stmt))}';
    return out;
}

i = 3;

// the following line is equivalent to while(i>=0) { alert(i); i-- }:
eval(Z('if(i>=0) { alert(i); i-- }'))



Read more about diagonalization and its use by Cantor and Gödel here.

UPDATE: a nicer code snippet by Matt Kaczmarek below.


special = "/**/"
function Z (stmt){
    stmt = stmt.replace (special, "\'" + stmt + "\'");
    return stmt;
}

i = 3;

// the following line is equivalent to while(i>=0) { alert(i); i-- }:
eval(Z('if(i>=0) {alert(i); i-- ; eval(Z(/**/))}'));
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s