Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

How to add 1 to every item in a stack in postscript?

I'm really struggling with the syntax in postscript. The program is given 6 values in a stack and needs to return the stack in the same order with 1 being added to every item. I am lost at this point, the program below is the closest I can get. This currently takes a stack and adds 2 to the last value in it.

/map {
    1 dict begin
    
    count 0 gt %if more than 0 on stack
    {   
        /x exch def %get first value
        x 1 add
        /x
        
    }if
    
    end
} def
question from:https://stackoverflow.com/questions/65928774/how-to-add-1-to-every-item-in-a-stack-in-postscript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Probably the easiest way is to wrap the values in an array. Then you can use a forall loop to operate on each item.

/map {
    6 array astore
    {
        1 add
    } forall
} def

If you want to avoid creating an array, you can use roll to rearrange the items on the stack.

/map {
    6 {
        1 add
        6 1 roll
    } repeat
} def

Also note, in your code you probably don't want that last /x (it leaves the name on the stack where it will probably get in the way later). And since the top item on the stack is already the top item on the stack, you don't need /x exch def x. However, you could continue in that style and just make definitions for all 6 values.

/map {
    /z exch def
    /y exch def
    /x exch def
    /w exch def
    /v exch def
    /u exch def
    u 1 add
    v 1 add
    w 1 add
    x 1 add
    y 1 add
    z 1 add
} def

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...