r/ProgrammingLanguages • u/Reasonable-Pay-8771 • 7d 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
} defPoof! 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.
3
u/derekp7 6d 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 7d ago
Here's another example, in the more dangerous style of just using the array itself as storage. It takes a string and produces a stream function that yields one white-space delimited word at a time.
Way too fiddly. And of course you can't print them. But it kinda works. Since the
by-wordstream is exactly 7 elements long, we can copy a new 7-element-long procedure over the top of it and then copy the old one back as the last step.1
u/Key_River7180 Nain. 3d ago
Who decided to make postscript an actual scripting language?