C Style Looping

Idio supports the C for and while style of looping. There is a name-clash so the C variant is named C/for.

The standard C form has four elements:

for (init; test; incr) body

which allow for fairly arbitrary init, test and incr expressions.

In Idio, each loop variable gets its own (name init incr) tuple in the var-clauses section:

C/for var-clauses test body

name and the init expression are straight-forward enough, the incr expression is the value to be used next time round the loop. In other words, you are not looking to modify the variable name but rather calculating its value for next time round.

simple-C-for.idio
C/for (
        (i 0 (i + 1))
      ) (i lt 5) {
  printf "i is %d\n" i
}
$ idio simple-C-for
i is 0
i is 1
i is 2
i is 3
i is 4

while

while is, of course, simply a C/for without the var-clauses element:

simple-C-while.idio
i := 0

while (i lt 5) {
  printf "i is %d\n" i
  i = i + 1
}
$ idio simple-C-while
i is 0
i is 1
i is 2
i is 3
i is 4

break / continue

The functions break and continue are available in the body element of both C/for and while:

simple-C-for-2.idio
C/for (
       (i 0 (i + 1))
) (i lt 5) {
  (cond
   ((i eq 1) (continue))
   ((i eq 4) (break))
   (else {
     printf "i is %d\n" i
   }))
}
$ idio simple-C-for-2
i is 0
i is 2
i is 3

Last built at 2024-05-21T06:11:38Z+0000 from 77077af (dev) for Idio 0.3