I'm trying to implement drawing Pifagor's Tree in PostScript via recursion, but something went wrong - my right cathet of each triangle is't painting so my right part is empty. What am i doing wrong? here's the code:
newpath
300 300 moveto
size 0 rlineto
/tree{
1 sub /n exch def
n 0 le { 1}
{
/size exch def %takes size from past stroke(for this case it is number 90 in row №18)
0 size rlineto
size -1 mul 0 rlineto
0 size -1 mul rlineto
0 size rlineto
45 rotate
/size size 2 sqrt mul 0.5 mul def
size 0 rlineto
size n tree
270 rotate
size 0 rlineto
size n tree
}ifelse
} def
90 31 tree %size of square's side, number of iterations
stroke showpage
Well, your program uses 'size' before you define it, in line 3, so it immediately throws an 'undefined' error before drawing anything. I fixed that by changing it to 90:
newpath
300 300 moveto
size 0 rlineto
Your program draws the left side of the tree first, recursing through 'tree'. Then it steps back up a level and draws the matching right side at each level, again recursing as required.
But after we've descended to the smallest object, size has been defined as a tiny number, so the other side is drawn, just so small you can't see it.
You seem to be trying to treat PostScript dictionary entries as if they were local variables in a C function, PostScript doesn't work that way. There are no variables, there are only dictionaries and their contents.
Your code defines /n and /size in the current dictionary. Then it calls 'tree' again, which redefines /n and /size in the current dictionary and so on.
Instead of defining n and size in the current dictionary, you probably want to leave them on the stack. This does mean that if recursion goes deep enough you will get a stackoverflow error, but that's what you would get with any language eventually.
Note that your current program doesn't leave the stack untouched, if n is less than or equal to zero you don't pop 'size' from the stack and you push a '1' onto the stack. So you'll have to address that too.