Search code examples
pari-gp

How to make multi-line nested for loops in PARI/GP?


How can I make nested loops in PARI/GP that span multiple lines at each level? I often have to do multiple things inside for loops, and for readability I don't like writing my loops on a single line. For a loop over one variable, I've been doing this:

for(i=1,10,{
    printf("%u\n",i);
})

However, for nested loops I've only managed to put line-breaks at one level. This works:

for(i=1, 10, for(j=1, 10, {
     printf("%2u\t%2u\n", i, j);
}));

This also works:

for(i=1, 10, {
     for(j=1, 10, printf("%2u\t%2u\n", i, j));
});

However, this is what I'd really like to do:

for(i=1, 10, {
     for(j=1, 10, {
          printf("%2u\t%2u\n", i, j);
     });
});

This last example doesn't work; it gives an error:

  ***   sorry, embedded braces (in parser) is not yet implemented.
... skipping file 'nested_for.gp'
  ***   at top-level: printf("%2u\t%2u\n",
  ***                 ^--------------------
  *** printf: not a t_INT in integer format conversion: i.
  ***   Break loop: type 'break' to go back to GP

I'm using PARI/GP 2.5.3 on OS X 10.8.3. I write my scripts into a file nested_for.gp and run them using gp ./nested_for.gp at Bash.


Solution

  • Contrary to what we expect from C-like syntax, braces don't define a block in GP. They only allow to split a sequence of instructions on multiple consecutive lines. They don't nest; on the other hand, you can nest loops inside a single { } block:

    {
      for (i = 1, 10,
        for (j = 1, 10,
          print (i+j))) 
    }
    

    Multi-line commands are usually found in user functions, and may look more natural in such a context:

    fun(a, b) =
    {
      for (i = 1, a,
        for (j = 1, b, 
          print (i+j)));
    }