定义一个回文运算符,在 postscript 中以相反的顺序复制堆栈上的值

问题描述 投票:0回答:2

定义一个回文运算符,以相反的顺序复制堆栈上的值。

这就是我到目前为止所拥有的,但它没有做我想做的事情

/palindrome {
1 dict begin
 count 1 gt
{
/first exch def
/second exch def
temp1 = first
temp2 = last
first = last
last = temp1
   }
} def

post postscript
2个回答
1
投票

您在那里写的大部分内容在 PostScript 中没有任何意义:

/palindrome
{
  1 dict begin
  count 1 gt 
  {
    /first exch def
    /second exch def
%% The following four lines are not valid PostScript
    temp1 = first
    temp2 = last
    first = last
    last = temp1
%% There is no '=' assignment operator in PostScript, in PS the = operator
%% pops one object from the stack and writes a text representation to stdout.
%% You have not defined any of the keys temp1, temp2 or last
%% in any dictionary. If executed I would expect this program to throw an
%% 'undefined' error in 'temp1'
  }
%% Given the 'count 1 gt' at the opening brace, I would expect this executable
%% array to be followed by a conditional, such as 'if'. Since it isn't this just
%% leaves the executable array '{....}' on the stack
} def

所以总的来说,我希望这个 PostScript 函数将一个布尔值推送到操作数堆栈上,true 或 false 取决于执行时堆栈上是否至少有 2 个对象,然后将可执行数组推送到操作数堆栈上然后退出。

如果我这样做,我会将堆栈存储到一个数组中,然后将该数组卸载回堆栈,然后从头到尾迭代该数组。比如:

%!

/palindrome
{
  count array astore
  aload
  dup length 1 sub -1 0 {
   1 index exch get
    exch
  } for
  pop
} def

(line 1)
2
3

(before palindrome\n) print
pstack
palindrome
(after palindrome\n) print
pstack

也可以(我在这里有一个工作示例)通过使用 for 循环和操作堆栈来一次完成此操作,而无需定义任何额外的存储对象(字典或数组)。对我来说,这似乎是一个更优雅的解决方案,并留给读者作为练习:-)


0
投票

我知道这很旧,但可能对某人有用。

使用内置的复制和反向功能,

%!

% n reverse - reverses top n stack elements
/reverse {
  -1 2 { 1 roll } for
} bind def

% makes a palindrome from the stack
/palin {
  count copy           % add a copy of the stack to the stack
  count 2 idiv reverse % reverse the top half of the stack
} bind def

[7 8] 5 (hello)        % put some items on the stack

pstack  % before - [7 8] 5 (hello)
palin
pstack  % after  - [7 8] 5 (hello) (hello) 5 [7 8]
© www.soinside.com 2019 - 2024. All rights reserved.