Aug. 28th, 2018 [entries|reading|network|archive]
simont

[ userinfo | dreamwidth userinfo ]
[ archive | journal archive ]

Tue 2018-08-28 09:18
ScriptPost

I've been handwriting PostScript on occasion for more than half my life – it's one of those odd side skills that comes in handy more often than you might think – and somehow I think yesterday was the first occasion I can remember when I had to swap the values of two variables.

Usually, in a language where the assignment operator can only change one variable at a time, the idiom for swapping two variables requires three statements, using a temporary variable to save one value in at the point where you've just copied the other value from one variable to the other (so they both hold the same value).

PostScript is such a language. The syntax for doing a swap that way (supposing the variables you're swapping are called foo and bar) would be

/tmp foo def
/foo bar def
/bar tmp def

in which, for example, /tmp pushes a variable name on the operand stack; foo pushes a variable's value; and the def operator pops both of those operands back off and writes the given value into the variable identified by the given name.

But this is excessively roundabout. PostScript may only let you assign one variable at a time, but its stack structure lets you avoid defining a temporary name: in order to save the old value of the first variable, you only have to push it temporarily on the operand stack, and recover it after the redefinition of the other. For example:

bar            % push the original value of bar
/bar foo def % set the final value of bar
/foo exch def % set foo to the value pulled back off the stack

But a neater way avoids even the need for that exch:

/foo bar       % parameters for the 'def' that will set foo
/bar foo % parameters for the 'def' that will set bar
def % set bar, using the second pair of params
def % set foo, using the first pair

or, once you're using it in anger and not explaining it every time,

/foo bar /bar foo def def

I thought that was unexpectedly cute! It's got the same set of words as the two separate assignment operations ‘/foo bar def’ and ‘/bar foo def’, but it uses the fact that PostScript assignment ‘statements’ are in some sense not atomic specifically, that the evaluation of their RHS and the enaction of the assignment itself can be separated – to interleave those two statements in a way that avoids the usual problem.

And that's why I think I can't ever have had to do that before – if I had, then surely I'd have run into this mild cuteness already!

Link6 comments | Reply
navigation
[ viewing | August 28th, 2018 ]
[ go | Previous Day|Next Day ]