c2lang / c2compiler

the c2 programming language
c2lang.org
Apache License 2.0
704 stars 49 forks source link

Proposal to `then {} else {}` after a loop #107

Closed thanhminhmr closed 5 years ago

thanhminhmr commented 5 years ago

Currently, things look like this:

bool isOK = true;
for (i8 index = 0; index < 10; index++) {
    if (doSomething(index) == false) {
        isOK = false;
        break;
    }
}
if (isOK) {
    finishTheJob();
} else {
    screamAndThrowEverything();
}

With the then {} else {}, things should look like this:

for (i8 index = 0; index < 10; index++) {
    if (doSomething(index) == false) break;
} then {
    finishTheJob();
} else {
    screamAndThrowEverything();
}

The similar syntax should be the same with while and do while loop. This should make the code shorter but easier to understand, remove the necessity for the extra bool and should speed things up a bit compared to the if then version (remove the extra bool and the condition check). Personally I meet a lot of case where I wish this syntax is a thing. What do everyone think about this idea?

lerno commented 5 years ago

I would usually refactor this as:

bool helper_func() {
   for (i8 index = 0; index < 10; index++) {
      if (!doSomething(index)) return false;
   }
   return true;
}

...
if (helper_func()) {
  finishTheJob();
} else {
   screamAndThrowEverything();
}

There are three alternative possibilites that comes to mind if one wanted to solve this in some more uniform manner:

  1. All statments return a value
  2. Statment expressions
  3. Inner functions (or anonymous) functions.

With the third, the code could look like this:

func void do_job() {
   load_jobs();

   func bool helper() {
      for (i8 index = 0; index < 10; index++) {
         if (!doSomething(index)) return false;
      }
      return true;
   }

   if (helper()) {
      finishTheJob();
   } else {
      screamAndThrowEverything();
   }
   cleanup_jobs();
}
bvdberg commented 5 years ago

I think the meaning of a for/while/etc loop should be a loop and not have a conditional meaning at the end. In my opinion this only makes the languages more complex, while it should consist of easy to understand operations.