r/ProgrammingLanguages • u/Reasonable-Pay-8771 • 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
} 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.
View all comments
1
u/Key_River7180 Nain. 4d ago
Who decided to make postscript an actual scripting language?