If then else - control structures

Until now, all operations of our PostScript machine are strictly linear. All code is executed once and without conditions. But without conditional execution, the machine is not Turning complete.

This problem is very easy to solve. We do have to modify our interpreter only slightly. We have to build a counter for the depth of the sequence, because a sequence may have sub-sequences.

What we need, is values (true, false), operators that can compare (equal, bigger, lower) and reverse (not) and operators. There will not be a Boolean type: 1 is true and 0 is false. We create an utility function to compare values.

Javascript

Javascript Editor

Javascript

We try it out.

Javascript Editor

We now are ready to construct the first conditional operator if.

Javascript

We try it out.

Javascript Editor

We can build a recursive functiom like factorial.

Javascript Editor

It is better to use the stack and not variables in recursion because of the variable scope. Note that there is no global scope on this page, so when you run just factorial here, you get an error.

Javascript Editor

We can also invent a mod operator.

Javascript Editor

Can we make also the greatest divisor? Stack hhandling is challenging, but gcd is quite similar to mod. Note that you can space and comment your code to make it readable.

Javascript Editor

My Journey to PostScript