-2

My question is, how would I go about making a function that serves the same purpose of the for loop, without using any loop method.

function fl (initial, condition, iterator, code){
    i = initial;
    if(condition){
        code()
    }
    i = i + iterator
    // Somehow repeat without using any loop
}

// The function would then be utilized like so

fl(0, i <= 5, 1, function(){
    console.log("This is a loop")
}

The parallel of the loop would be

for(i = 0, i <= 5, i++){
    console.log("This is a loop")
}

Is this even possible?

  • 3
    you could recursively call fl again at the end of the function. but the real question is, why would you want to do this? – Caleb May 3 at 0:45
  • @Caleb, Primarily for language design. If I were to create a programming language I'd want it to be as boot-strapped as it can be. I wouldn't want to have to rely on another language as the backbone for concepts that can be recreated. – baranskistad May 3 at 0:53
  • 1
    Think about how FORTH does loops and if statements. There are only 9 primitives needed to make a FORTH interpreter and the important one for loops and if statements is a "branch on zero" operation. en.wikipedia.org/wiki/… – Jerry Jeremiah May 3 at 3:36
  • Then you don't want javascript functions, operators and variables. – Goyo May 3 at 6:27
  • @Goyo I just used javascript as an example, as it is one of the most widely known languages. – baranskistad May 4 at 0:36
4

Iteration and tail-recursion are equivalent. So, all you need to implement a Turing-complete programming language are function calls.

Think about the λ-calculus: it is Turing-complete, and yet it only has two elements: creating functions and applying functions. It doesn't have loops or conditionals. It doesn't even have numbers, booleans, or any datatype at all except for functions. And yet, you can implement anything in λ-calculus, booleans, numbers, conditionals, loops, you name it.

Scheme was designed to be close to λ-calculus, and in turn ECMAScript is closely descended from Scheme, so it is no surprise that this can be expressed easily in ECMAScript as well.

I will give you a WHILE loop as an example:

function whileLoop(condition, body) {
    if (!condition()) { return; }

    body();
    whileLoop(condition, body);
}

let i = 0;
whileLoop(() => i < 10, () => { i++; console.log(i); });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.