wesleydashner
wesleydashner

Reputation: 45

How do I move the number at the top of the stack to the bottom without using roll in PostScript?

I'd like to define something in the dictionary, call it top, such that it moves the number at the top of the stack to the bottom and keeps all the other numbers in place. I'd like to do this without using the roll operator. I've been trying things for hours but am new to PostScript and am getting frustrated since it seems like such a simple task that I could solve so quickly in any other language.

This is what I've got so far but don't know why it won't work:

/top {
  1 dict begin
  count 1 gt 
    {
      /first exch def
      /second exch def
      first top second
    }
} def

Upvotes: 1

Views: 336

Answers (1)

luser droog
luser droog

Reputation: 19504

You could store everything in an array and then get or getinterval the pieces you want.

/first { 0 get } def
/rest { 1  1 index length 1 sub  getinterval } def

% a b c d ... n  --  b c d ... n a
/top {
  1 dict begin
    count array astore /stack exch def
    stack rest aload pop
    stack first
  end
} def

This could also be factored more.

<<
    /first { 0 get }
    /rest  { 1  1 index length 1 sub  getinterval }
    /aa    { array astore }
    /:=    { exch def }
    /spill { aload pop }
>> currentdict copy

% a b c d ... n  --  b c d ... n a
/top {
  1 dict begin
    count aa /stack :=
    stack rest spill
    stack first
  end
} def

/spill could be written several ways

/spill { {} forall } def

or even

% assumes array does not contain executable names or arrays
/spill { cvx exec } def

Edit: I may have misunderstood the question and shown the reverse of what was wanted. The above code does a count -1 roll. To do a count 1 roll moving the the top element to the bottom,

/head { 0  1 index length 1 sub  getinterval } def
/last { dup length 1 sub  get } def

% a b c ... x y z  --  z a b c .. x y
/top {
  1 dict begin
    count array astore /stack exch def
    stack last
    stack head aload pop
  end
} def

Upvotes: 1

Related Questions