append

arrayとstring両対応のappendを作る。
オペレータ名はHaskellをまねて++にした。

/++ {
  5 dict begin
  /arraytype {array} def
  /stringtype {string} def
  /y exch def
  /x exch def
  x length y length add x type exec /r exch def
  r x r copy length y putinterval
  r end
} def

実行例

GS>(abc) (de) ++ ==
(abcde)
GS>[1 2 3] [4 5] ++ ==
[1 2 3 4 5]

なるべくスタックを使うようにしたバージョン

/++ {
  3 dict begin
  /arraytype {array} def
  /stringtype {string} def
  2 copy length exch length add 1 index type exec /r exch def
  exch r copy length exch r 3 1 roll putinterval
  r end
} def

おぼえがき

type命令は実行属性のついたarraytype,stringtype等の名前を返す。
よって、それらのオペレータを定義しておけば、タイプに応じた処理が出来る。

GS>[1 2 3] type ==
arraytype
GS>(abc) type ==
stringtype
GS>/arraytype {(Hairetsu Desu.) =} def
GS>/stringtype {(Mojiretsu Desu.) =} def
GS>[1 2 3] type exec
Hairetsu Desu.
GS>(abc) type exec
Mojiretsu Desu.

x y copy はxの内容がyにコピーされる。実行後はxの内容が残る。
x n y putinterval はyの内容がxのn番目(0スタート)以降にコピーされる。実行後は何も残らない。