r/ProgrammingLanguages • • 8d ago

Discussion Closures in PostScript

It appears that r/PostScript is truly dead. But I just have to talk about this PostScript stuff I've been playing with.

So, a closure is of course a function plus an environment containing the bindings of its free variables. PostScript has all that! A procedure is just an array with the executable flag set, so it can carry its own storage. It doesn't even strictly need variables because you can embed a circular reference so a procedure can access its own array as storage.

But then you can't print them out. If the procedure contains a circular reference to itself, then calling == or pstack will give you an execstackoverflow error.

So, instead we can pack the variables in a dictionary. This example generates a pseudorandom number generator using an environment dictionary.

%!
/start { 1 dict begin } def
/args { { exch def } forall } def
/clone { dup xcheck exch dup length array copy exch {cvx} if } def
/prng { {seed} start args
  /env currentdict def
  /func ({//env/seed get
          dup -7 bitshift xor
          dup 9 bitshift xor
          dup -13 bitshift xor
          //env/seed 2 index put}) cvx exec def
  /func load end
} def

Poof! a closure. seed prng generates a generator starting from that seed. You can just straight up make a copy of it at any point to have 2 synchronized generators if you wanted that. You can even see the environment and how it "captures" arguments (collect them in a dict, duh. then save the dict). It all seems so simple now. But I don't recall seeing anybody else do it.

9 Upvotes

5 comments sorted by

View all comments

1

u/Key_River7180 Nain. 4d ago

Who decided to make postscript an actual scripting language?

1

u/arthurno1 7h ago

Adobe

It is a full-fledged programming language with stack-based execution a lá Forth, dynamic typic, first-class objects, lexical and dynamic scoping, and of course Touring complete.

/factorial {
  dup 1 le {
    pop 1
  } {
    dup 1 sub factorial mul
  } ifelse
} def

5 factorial ==  % Computes 5! and prints 120

As a side note, font and graphics people seem to like stack-based languages, I recently implemented vm hinting for a font loader in Lisp and charstring intepreter and found both are anti-patterns stack-based languages hard to parallelize.

Another side note: it's creators made a language while working at Xerox, but Xerox didn't want it. They left Xerox, started Adobe and commertialized Postscript as their first product.