/
List.pm
257 lines (220 loc) Β· 8.07 KB
/
List.pm
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
class Range { ... }
class List does Positional {
# declared in BOOTSTRAP.pm:
# is Iterable; # parent class
# has Mu $!items; # RPA of our reified elements
# has $!flattens; # true if this list flattens its parcels
# has $!nextiter; # iterator for generating remaining elements
method new(|$) {
my Mu $args := pir::perl6_current_args_rpa__P();
nqp::shift($args);
nqp::p6list($args, self.WHAT, Mu);
}
method Bool() { self.gimme(1).Bool }
method Int() { self.elems }
method Numeric() { self.elems }
method end() { self.elems - 1 }
multi method Str(List:D:) { self.join(' ') }
method fmt($format = '%s', $separator = ' ') {
self.map({ .fmt($format) }).join($separator);
}
method flat() { self.flattens
?? self
!! nqp::p6list(nqp::list(self), List, Bool::True)
}
method list() { self }
method flattens() { $!flattens }
method Parcel() {
pir::defined($!items) or
nqp::bindattr(self, List, '$!items', nqp::list());
my Mu $rpa := nqp::clone($!items);
nqp::push($rpa, $!nextiter) if $!nextiter.defined;
nqp::p6parcel($rpa, Any);
}
method at_pos($pos is copy) is rw {
$pos = $pos.Int;
self.exists($pos)
?? nqp::atpos($!items, nqp::unbox_i($pos))
!! Mu
}
method eager() { self.gimme(*); self }
method elems() {
# Get as many elements as we can. If gimme stops before
# reaching the end of the list, assume the list is infinite.
my $n = self.gimme(*);
$!nextiter.defined ?? nqp::p6box_n('Inf') !! $n
}
method exists(\$pos) {
self.gimme($pos + 1);
nqp::p6bool(nqp::existspos($!items, nqp::unbox_i($pos)))
}
method gimme($n) {
# create $!items RPA if it doesn't already exist
pir::defined($!items) or
nqp::bindattr(self, List, '$!items', nqp::list());
# loop through iterators until we have at least $n elements
my $count = nqp::p6box_i(nqp::elems($!items));
my $eager = Whatever.ACCEPTS($n);
while $!nextiter.defined && ($eager
?? !$!nextiter.infinite
!! ($count < $n)) {
$!nextiter.reify($eager ?? Whatever !! $n - $count);
$count = nqp::p6box_i(nqp::elems($!items));
}
# return the number of elements we have now
$count
}
method infinite() {
$!nextiter.defined && $!nextiter.infinite;
}
method iterator() {
# Return a reified ListIter containing our currently reified elements
# and any subsequent iterator.
my $iter := nqp::create(ListIter);
nqp::bindattr($iter, ListIter, '$!nextiter', $!nextiter);
nqp::bindattr($iter, ListIter, '$!reified', self.Parcel());
$iter;
}
method munch(\$n) {
self.gimme($n) if nqp::not_i(nqp::istype($n, Int))
|| nqp::not_i(pir::defined($!items))
|| nqp::islt_i(nqp::elems($!items), nqp::unbox_i($n));
nqp::p6parcel(
pir::perl6_shiftpush__0PPi(nqp::list(), $!items, nqp::unbox_i($n)),
Any
)
}
method pick($n is copy = 1) {
## We use a version of Fisher-Yates shuffle here to
## replace picked elements with elements from the end
## of the list, resulting in an O(n) algorithm.
my $elems = self.elems;
fail ".pick from infinite list NYI" if $!nextiter.defined;
$n = +$Inf if nqp::istype($n, Whatever);
$n = $elems if $n > $elems;
return self.at_pos($elems.rand.floor) if $n == 1;
my Mu $rpa := nqp::clone($!items);
my $i;
my Mu $v;
gather while $n > 0 {
$i = $elems.rand.floor.Int;
$elems--; $n--;
$v := nqp::atpos($rpa, nqp::unbox_i($i));
# replace selected element with last unpicked one
nqp::bindpos($rpa, nqp::unbox_i($i),
nqp::atpos($rpa, nqp::unbox_i($elems)));
take-rw $v;
}
}
method pop() {
my $elems = self.elems;
fail '.pop from an infinite list NYI' if $!nextiter.defined;
$elems > 0
?? nqp::pop($!items)
!! fail 'Element popped from empty list';
}
method push(*@values) {
my $pos = self.elems;
fail '.push on infinite lists NYI' if $!nextiter.defined;
self.STORE_AT_POS($pos++, @values.shift) while @values;
}
method roll($n is copy = 1) {
my $elems = self.elems;
fail ".roll from infinite list NYI" if $!nextiter.defined;
$n = +$Inf if nqp::istype($n, Whatever);
return self.at_pos($elems.rand.floor) if $n == 1;
gather while $n > 0 {
take nqp::atpos($!items, nqp::unbox_i($elems.rand.floor.Int));
$n--;
}
}
method reverse() {
self.gimme(*);
fail 'Cannot reverse and infinite list' if self.infinite;
my Mu $rev := nqp::list();
my Mu $orig := nqp::clone($!items);
nqp::push($rev, nqp::pop($orig)) while $orig;
my $rlist := nqp::create(self.WHAT);
nqp::bindattr($rlist, List, '$!items', $rev);
$rlist;
}
method shift() {
# make sure we have at least one item, then shift+return it
self.gimme(1)
?? nqp::shift($!items)
!! fail 'Element shifted from empty list';
}
method sort($by = &infix:<cmp>) {
# We defer to Parrot's ResizablePMCArray.sort method here.
# Instead of sorting elements directly, we sort a Parcel of
# indices from 0..^$list.elems, then use that Parcel as
# a slice into self.
# Range is currently optimized for fast Parcel construction.
my $index := Range.new(0, self.elems, :excludes_max).reify(*);
my Mu $index_rpa := nqp::getattr($index, Parcel, '$!storage');
# if $by.arity < 2, then we apply the block to the elements
# for sorting.
if ($by.?count // 2) < 2 {
my $list = self.map($by).eager;
$index_rpa.sort(-> $a, $b { $list[$a] cmp $list[$b] || $a <=> $b });
}
else {
my $list = self.eager;
$index_rpa.sort(-> $a, $b { $by($list[$a],$list[$b]) || $a <=> $b });
}
self[$index];
}
method classify(&test) {
my %result;
for @.list {
my $k = test $_;
%result{$k} //= [];
%result{$k}.push: $_;
}
%result.pairs;
}
multi method gist(List:D:) { self.Str }
multi method perl(List:D \$self:) {
self.gimme(*);
self.Parcel.perl ~ '.list'
~ (nqp::iscont($self) ?? '.item' !! '')
}
method REIFY(Parcel \$parcel) {
nqp::splice($!items, nqp::getattr($parcel, Parcel, '$!storage'),
nqp::elems($!items), 0);
$parcel
}
method STORE_AT_POS(\$pos, Mu \$v) is rw {
nqp::bindpos($!items, nqp::unbox_i($pos), $v)
}
method ARGLIST_FLATTENABLE() { self.gimme(*); $!items }
multi method DUMP(List:D:) {
self.DUMP-ID() ~ '('
~ ("\x221e " if self.infinite) ~
~ ':items(' ~ DUMP($!items) ~ '), '
~ ':nextiter(' ~ DUMP($!nextiter) ~ ')'
~ ')'
}
}
sub eager(|$) {
nqp::p6parcel(pir::perl6_current_args_rpa__P(), Any).eager
}
sub flat(|$) {
nqp::p6list(pir::perl6_current_args_rpa__P(), List, Bool::True)
}
sub list(|$) {
nqp::p6list(pir::perl6_current_args_rpa__P(), List, Mu)
}
proto infix:<xx>(|$) { * }
multi infix:<xx>() { fail "No zero-arg meaning for infix:<xx>" }
multi infix:<xx>(Mu \$x) { $x }
multi infix:<xx>(Mu \$x, $n is copy) {
$n = $Inf if Whatever.ACCEPTS($n);
GatherIter.new({ take $x while $n-- > 0; }, :infinite($n == $Inf)).list
}
proto sub pop(|$) {*}
multi sub pop(@a) { @a.pop }
proto sub shift(|$) {*}
multi sub shift(@a) { @a.shift }
proto sub push(|$) {*}
multi sub push(@a, *@elems) { @a.push: @elems }