-
Notifications
You must be signed in to change notification settings - Fork 0
/
lists.ps
97 lines (79 loc) · 1.78 KB
/
lists.ps
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
%!PS
%%
%% Section: Array manipulation
%%
% Retrieve the last element of an array
/last { % <array> last <any>
dup length 1 sub get
} bind def
% Return a copy of an array in reverse order
/rev { % <array> rev <array>
[exch aload pop 2 1 counttomark 2 sub {-1 roll} for]
} bind def
% Append a value to an array
/append { % <array> <value> append <array>
exch dup length 1 add array
dup 4 -1 roll 4 2 roll
exch 0 exch
putinterval
1 index dup length 1 sub 3 -1 roll put
} bind def
% Prepend a value to an array
/prepend { % <array> <value> prepend <array>
exch
dup length 1 add array
dup count 1 roll exch 1 exch
putinterval
exch dup 3 -1 roll 0 exch put
} bind def
%%
%% Section: Dictionary manipulation
%%
% Return a dictionary's keys as an array
/keys { % <dict> keys <array>
begin
currentdict {pop} forall
currentdict length array astore
end
} bind def
% Return a dictionary's values as an array
/values { % <dict> values <array>
begin
currentdict {exch pop} forall
currentdict length array astore
end
} bind def
% Return a dictionary's concatenated key/value pairs as an array
/entries { % <dict> entries <array>
begin
currentdict {} forall
currentdict length 2 mul array astore
end
} bind def
% Return a copy of a dictionary with its keys and values swapped
/flip { % <dict> flip <dict>
dup length dict exch
begin
currentdict {
exch
2 index 3 1 roll
put
} forall
end
} bind def
%%
%% Section: Operand stack manipulation
%%
% Return nth operand if index >= 0, nth-last otherwise
/nth { % <any...> <index> nth <any>
dup 0 lt { count add 1 sub } if
index
} bind def
% Remove the last entry on the operand stack
/shift { % <any> shift -
count -1 roll pop
} bind def
% Push an operand onto the end of the stack
/unshift { % <any> unshift -
count 1 roll
} bind def