r/ProgrammingLanguages • • 17d 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

3

u/derekp7 15d ago

I believe I recall the closure example from the blue book... Looks like it is on page 133.

The language I'm working on is inspired by PostScript, what I have is a "parentdict" keyword that gets replaced by the wrapping function's active dictionary at execution time, providing a cleaner interface (basically syntactic sugar for the same mechanism).  Eventually I'll get around to my full writeup on this.

1

u/Reasonable-Pay-8771 15d ago

Wow. I guess you're right. It's page 127 in the printed book. It does show putting the dictionary into the proc. I suppose my innovation is just in the style and syntax, some of which (immediate names) wasn't available in the language when the Blue Book was published (immediate names were added in "level 1.5" some time between PLRM 1ed and 2ed).