• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lunarmodules / Penlight / 474

01 Feb 2024 02:24PM UTC coverage: 89.675% (+0.8%) from 88.873%
474

push

appveyor

web-flow
docs: Fix typos (#462)

7 of 7 new or added lines in 2 files covered. (100.0%)

140 existing lines in 18 files now uncovered.

5489 of 6121 relevant lines covered (89.67%)

345.29 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.83
/lua/pl/List.lua
1
--- Python-style list class.
2
--
3
-- **Please Note**: methods that change the list will return the list.
4
-- This is to allow for method chaining, but please note that `ls = ls:sort()`
5
-- does not mean that a new copy of the list is made. In-place (mutable) methods
6
-- are marked as returning 'the list' in this documentation.
7
--
8
-- See the Guide for further @{02-arrays.md.Python_style_Lists|discussion}
9
--
10
-- See <a href="http://www.python.org/doc/current/tut/tut.html">http://www.python.org/doc/current/tut/tut.html</a>, section 5.1
11
--
12
-- **Note**: The comments before some of the functions are from the Python docs
13
-- and contain Python code.
14
--
15
-- Written for Lua version Nick Trout 4.0; Redone for Lua 5.1, Steve Donovan.
16
--
17
-- Dependencies: `pl.utils`, `pl.tablex`, `pl.class`
18
-- @classmod pl.List
19
-- @pragma nostrip
20

21
local tinsert,tremove,concat,tsort = table.insert,table.remove,table.concat,table.sort
160✔
22
local setmetatable, getmetatable,type,tostring,string = setmetatable,getmetatable,type,tostring,string
160✔
23
local tablex = require 'pl.tablex'
160✔
24
local filter,imap,imap2,reduce,transform,tremovevalues = tablex.filter,tablex.imap,tablex.imap2,tablex.reduce,tablex.transform,tablex.removevalues
160✔
25
local tsub = tablex.sub
160✔
26
local utils = require 'pl.utils'
160✔
27
local class = require 'pl.class'
160✔
28

29
local array_tostring,split,assert_arg,function_arg = utils.array_tostring,utils.split,utils.assert_arg,utils.function_arg
160✔
30
local normalize_slice = tablex._normalize_slice
160✔
31

32
-- metatable for our list and map objects has already been defined..
33
local Multimap = utils.stdmt.MultiMap
160✔
34
local List = utils.stdmt.List
160✔
35

36
local iter
37

38
class(nil,nil,List)
160✔
39

40
-- we want the result to be _covariant_, i.e. t must have type of obj if possible
41
local function makelist (t,obj)
42
    local klass = List
304✔
43
    if obj then
304✔
44
        klass = getmetatable(obj)
288✔
45
    end
46
    return setmetatable(t,klass)
304✔
47
end
48

49
local function simple_table(t)
50
    return type(t) == 'table' and not getmetatable(t) and #t > 0
768✔
51
end
52

53
function List._create (src)
160✔
54
    if simple_table(src) then return src end
1,152✔
55
end
56

57
function List:_init (src)
160✔
58
    if self == src then return end -- existing table used as self!
768✔
59
    if src then
364✔
60
        for v in iter(src) do
1,048✔
61
            tinsert(self,v)
552✔
62
        end
63
    end
64
end
65

66
--- Create a new list. Can optionally pass a table;
67
-- passing another instance of List will cause a copy to be created;
68
-- this will return a plain table with an appropriate metatable.
69
-- we pass anything which isn't a simple table to iterate() to work out
70
-- an appropriate iterator
71
-- @see List.iterate
72
-- @param[opt] t An optional list-like table
73
-- @return a new List
74
-- @usage ls = List();  ls = List {1,2,3,4}
75
-- @function List.new
76

77
List.new = List
160✔
78

79
--- Make a copy of an existing list.
80
-- The difference from a plain 'copy constructor' is that this returns
81
-- the actual List subtype.
82
function List:clone()
160✔
83
    local ls = makelist({},self)
8✔
84
    ls:extend(self)
8✔
85
    return ls
8✔
86
end
87

88
--- Add an item to the end of the list.
89
-- @param i An item
90
-- @return the list
91
function List:append(i)
160✔
92
    tinsert(self,i)
608✔
93
    return self
608✔
94
end
95

96
List.push = tinsert
160✔
97

98
--- Extend the list by appending all the items in the given list.
99
-- equivalent to 'a[len(a):] = L'.
100
-- @tparam List L Another List
101
-- @return the list
102
function List:extend(L)
160✔
103
    assert_arg(1,L,'table')
24✔
104
    for i = 1,#L do tinsert(self,L[i]) end
161✔
105
    return self
24✔
106
end
107

108
--- Insert an item at a given position. i is the index of the
109
-- element before which to insert.
110
-- @int i index of element before whichh to insert
111
-- @param x A data item
112
-- @return the list
113
function List:insert(i, x)
160✔
114
    assert_arg(1,i,'number')
40✔
115
    tinsert(self,i,x)
40✔
116
    return self
40✔
117
end
118

119
--- Insert an item at the beginning of the list.
120
-- @param x a data item
121
-- @return the list
122
function List:put (x)
160✔
123
    return self:insert(1,x)
8✔
124
end
125

126
--- Remove an element given its index.
127
-- (equivalent of Python's del s[i])
128
-- @int i the index
129
-- @return the list
130
function List:remove (i)
160✔
131
    assert_arg(1,i,'number')
8✔
132
    tremove(self,i)
8✔
133
    return self
8✔
134
end
135

136
--- Remove the first item from the list whose value is given.
137
-- (This is called 'remove' in Python; renamed to avoid confusion
138
-- with table.remove)
139
-- Return nil if there is no such item.
140
-- @param x A data value
141
-- @return the list
142
function List:remove_value(x)
160✔
143
    for i=1,#self do
136✔
144
        if self[i]==x then tremove(self,i) return self end
138✔
145
    end
146
    return self
8✔
147
 end
148

149
--- Remove the item at the given position in the list, and return it.
150
-- If no index is specified, a:pop() returns the last item in the list.
151
-- The item is also removed from the list.
152
-- @int[opt] i An index
153
-- @return the item
154
function List:pop(i)
160✔
155
    if not i then i = #self end
8✔
156
    assert_arg(1,i,'number')
8✔
157
    return tremove(self,i)
8✔
158
end
159

160
List.get = List.pop
160✔
161

162
--- Return the index in the list of the first item whose value is given.
163
-- Return nil if there is no such item.
164
-- @function List:index
165
-- @param x A data value
166
-- @int[opt=1] idx where to start search
167
-- @return the index, or nil if not found.
168

169
local tfind = tablex.find
160✔
170
List.index = tfind
160✔
171

172
--- Does this list contain the value?
173
-- @param x A data value
174
-- @return true or false
175
function List:contains(x)
160✔
176
    return tfind(self,x) and true or false
24✔
177
end
178

179
--- Return the number of times value appears in the list.
180
-- @param x A data value
181
-- @return number of times x appears
182
function List:count(x)
160✔
183
    local cnt=0
8✔
184
    for i=1,#self do
40✔
185
        if self[i]==x then cnt=cnt+1 end
32✔
186
    end
187
    return cnt
8✔
188
end
189

190
--- Sort the items of the list, in place.
191
-- @func[opt='<'] cmp an optional comparison function
192
-- @return the list
193
function List:sort(cmp)
160✔
194
    if cmp then cmp = function_arg(1,cmp) end
44✔
195
    tsort(self,cmp)
32✔
196
    return self
32✔
197
end
198

199
--- Return a sorted copy of this list.
200
-- @func[opt='<'] cmp an optional comparison function
201
-- @return a new list
202
function List:sorted(cmp)
160✔
UNCOV
203
    return List(self):sort(cmp)
×
204
end
205

206
--- Reverse the elements of the list, in place.
207
-- @return the list
208
function List:reverse()
160✔
209
    local t = self
48✔
210
    local n = #t
48✔
211
    for i = 1,n/2 do
96✔
212
        t[i],t[n] = t[n],t[i]
48✔
213
        n = n - 1
48✔
214
    end
215
    return self
48✔
216
end
217

218
--- Return the minimum and the maximum value of the list.
219
-- @return minimum value
220
-- @return maximum value
221
function List:minmax()
160✔
222
    local vmin,vmax = 1e70,-1e70
8✔
223
    for i = 1,#self do
40✔
224
        local v = self[i]
32✔
225
        if v < vmin then vmin = v end
32✔
226
        if v > vmax then vmax = v end
32✔
227
    end
228
    return vmin,vmax
8✔
229
end
230

231
--- Emulate list slicing.  like  'list[first:last]' in Python.
232
-- If first or last are negative then they are relative to the end of the list
233
-- eg. slice(-2) gives last 2 entries in a list, and
234
-- slice(-4,-2) gives from -4th to -2nd
235
-- @param first An index
236
-- @param last An index
237
-- @return a new List
238
function List:slice(first,last)
160✔
239
    return tsub(self,first,last)
56✔
240
end
241

242
--- Empty the list.
243
-- @return the list
244
function List:clear()
160✔
245
    for i=1,#self do tremove(self) end
33✔
246
    return self
8✔
247
end
248

249
local eps = 1.0e-10
160✔
250

251
--- Emulate Python's range(x) function.
252
-- Include it in List table for tidiness
253
-- @int start A number
254
-- @int[opt] finish A number greater than start; if absent,
255
-- then start is 1 and finish is start
256
-- @int[opt=1] incr an increment (may be less than 1)
257
-- @return a List from start .. finish
258
-- @usage List.range(0,3) == List{0,1,2,3}
259
-- @usage List.range(4) = List{1,2,3,4}
260
-- @usage List.range(5,1,-1) == List{5,4,3,2,1}
261
function List.range(start,finish,incr)
160✔
262
    if not finish then
80✔
263
        finish = start
8✔
264
        start = 1
8✔
265
    end
266
    if incr then
80✔
267
    assert_arg(3,incr,'number')
48✔
268
    if math.ceil(incr) ~= incr then finish = finish + eps end
48✔
269
    else
270
        incr = 1
32✔
271
    end
272
    assert_arg(1,start,'number')
80✔
273
    assert_arg(2,finish,'number')
80✔
274
    local t = List()
80✔
275
    for i=start,finish,incr do tinsert(t,i) end
646✔
276
    return t
80✔
277
end
278

279
--- list:len() is the same as #list.
280
function List:len()
160✔
281
    return #self
16✔
282
end
283

284
-- Extended operations --
285

286
--- Remove a subrange of elements.
287
-- equivalent to 'del s[i1:i2]' in Python.
288
-- @int i1 start of range
289
-- @int i2 end of range
290
-- @return the list
291
function List:chop(i1,i2)
160✔
292
    return tremovevalues(self,i1,i2)
8✔
293
end
294

295
--- Insert a sublist into a list
296
-- equivalent to 's[idx:idx] = list' in Python
297
-- @int idx index
298
-- @tparam List list list to insert
299
-- @return the list
300
-- @usage  l = List{10,20}; l:splice(2,{21,22});  assert(l == List{10,21,22,20})
301
function List:splice(idx,list)
160✔
302
    assert_arg(1,idx,'number')
8✔
303
    idx = idx - 1
8✔
304
    local i = 1
8✔
305
    for v in iter(list) do
40✔
306
        tinsert(self,i+idx,v)
16✔
307
        i = i + 1
16✔
308
    end
309
    return self
8✔
310
end
311

312
--- General slice assignment s[i1:i2] = seq.
313
-- @int i1  start index
314
-- @int i2  end index
315
-- @tparam List seq a list
316
-- @return the list
317
function List:slice_assign(i1,i2,seq)
160✔
318
    assert_arg(1,i1,'number')
8✔
319
    assert_arg(1,i2,'number')
8✔
320
    i1,i2 = normalize_slice(self,i1,i2)
12✔
321
    if i2 >= i1 then self:chop(i1,i2) end
8✔
322
    self:splice(i1,seq)
8✔
323
    return self
8✔
324
end
325

326
--- Concatenation operator.
327
-- @within metamethods
328
-- @tparam List L another List
329
-- @return a new list consisting of the list with the elements of the new list appended
330
function List:__concat(L)
160✔
331
    assert_arg(1,L,'table')
8✔
332
    local ls = self:clone()
8✔
333
    ls:extend(L)
8✔
334
    return ls
8✔
335
end
336

337
--- Equality operator ==.  True iff all elements of two lists are equal.
338
-- @within metamethods
339
-- @tparam List L another List
340
-- @return true or false
341
function List:__eq(L)
160✔
342
    if #self ~= #L then return false end
482✔
343
    for i = 1,#self do
1,880✔
344
        if self[i] ~= L[i] then return false end
1,460✔
345
    end
346
    return true
420✔
347
end
348

349
--- Join the elements of a list using a delimiter.
350
-- This method uses tostring on all elements.
351
-- @string[opt=''] delim a delimiter string, can be empty.
352
-- @return a string
353
function List:join (delim)
160✔
354
    delim = delim or ''
24✔
355
    assert_arg(1,delim,'string')
24✔
356
    return concat(array_tostring(self),delim)
36✔
357
end
358

359
--- Join a list of strings. <br>
360
-- Uses `table.concat` directly.
361
-- @function List:concat
362
-- @string[opt=''] delim a delimiter
363
-- @return a string
364
List.concat = concat
160✔
365

366
local function tostring_q(val)
UNCOV
367
    local s = tostring(val)
×
368
    if type(val) == 'string' then
×
369
        s = '"'..s..'"'
×
370
    end
UNCOV
371
    return s
×
372
end
373

374
--- How our list should be rendered as a string. Uses join().
375
-- @within metamethods
376
-- @see List:join
377
function List:__tostring()
160✔
378
    return '{'..self:join(',',tostring_q)..'}'
24✔
379
end
380

381
--- Call the function on each element of the list.
382
-- @func fun a function or callable object
383
-- @param ... optional values to pass to function
384
function List:foreach (fun,...)
160✔
385
    fun = function_arg(1,fun)
12✔
386
    for i = 1,#self do
40✔
387
        fun(self[i],...)
32✔
388
    end
389
end
390

391
local function lookup_fun (obj,name)
392
    local f = obj[name]
24✔
393
    if not f then error(type(obj).." does not have method "..name,3) end
24✔
394
    return f
24✔
395
end
396

397
--- Call the named method on each element of the list.
398
-- @string name the method name
399
-- @param ... optional values to pass to function
400
function List:foreachm (name,...)
160✔
UNCOV
401
    for i = 1,#self do
×
402
        local obj = self[i]
×
403
        local f = lookup_fun(obj,name)
×
404
        f(obj,...)
×
405
    end
406
end
407

408
--- Create a list of all elements which match a function.
409
-- @func fun a boolean function
410
-- @param[opt] arg optional argument to be passed as second argument of the predicate
411
-- @return a new filtered list.
412
function List:filter (fun,arg)
160✔
413
    return makelist(filter(self,fun,arg),self)
12✔
414
end
415

416
--- Split a string using a delimiter.
417
-- @string s the string
418
-- @string[opt] delim the delimiter (default spaces)
419
-- @return a List of strings
420
-- @see pl.utils.split
421
function List.split (s,delim)
160✔
422
    assert_arg(1,s,'string')
16✔
423
    return makelist(split(s,delim))
24✔
424
end
425

426
--- Apply a function to all elements.
427
-- Any extra arguments will be passed to the function.
428
-- @func fun a function of at least one argument
429
-- @param ... arbitrary extra arguments.
430
-- @return a new list: {f(x) for x in self}
431
-- @usage List{'one','two'}:map(string.upper) == {'ONE','TWO'}
432
-- @see pl.tablex.imap
433
function List:map (fun,...)
160✔
434
    return makelist(imap(fun,self,...),self)
348✔
435
end
436

437
--- Apply a function to all elements, in-place.
438
-- Any extra arguments are passed to the function.
439
-- @func fun A function that takes at least one argument
440
-- @param ... arbitrary extra arguments.
441
-- @return the list.
442
function List:transform (fun,...)
160✔
443
    transform(fun,self,...)
16✔
444
    return self
16✔
445
end
446

447
--- Apply a function to elements of two lists.
448
-- Any extra arguments will be passed to the function
449
-- @func fun a function of at least two arguments
450
-- @tparam List ls another list
451
-- @param ... arbitrary extra arguments.
452
-- @return a new list: {f(x,y) for x in self, for x in arg1}
453
-- @see pl.tablex.imap2
454
function List:map2 (fun,ls,...)
160✔
455
    return makelist(imap2(fun,self,ls,...),self)
60✔
456
end
457

458
--- apply a named method to all elements.
459
-- Any extra arguments will be passed to the method.
460
-- @string name name of method
461
-- @param ... extra arguments
462
-- @return a new list of the results
463
-- @see pl.seq.mapmethod
464
function List:mapm (name,...)
160✔
UNCOV
465
    local res = {}
×
466
    for i = 1,#self do
×
467
      local val = self[i]
×
468
      local fn = lookup_fun(val,name)
×
469
      res[i] = fn(val,...)
×
470
    end
UNCOV
471
    return makelist(res,self)
×
472
end
473

474
local function composite_call (method,f)
475
    return function(self,...)
476
        return self[method](self,f,...)
24✔
477
    end
478
end
479

480
function List.default_map_with(T)
160✔
481
    return function(self,name)
482
        local m
483
        if T then
24✔
484
            local f = lookup_fun(T,name)
24✔
485
            m = composite_call('map',f)
36✔
486
        else
UNCOV
487
            m = composite_call('mapn',name)
×
488
        end
489
        getmetatable(self)[name] = m -- and cache..
24✔
490
        return m
24✔
491
    end
492
end
493

494
List.default_map = List.default_map_with
160✔
495

496
--- 'reduce' a list using a binary function.
497
-- @func fun a function of two arguments
498
-- @return result of the function
499
-- @see pl.tablex.reduce
500
function List:reduce (fun)
160✔
501
    return reduce(fun,self)
8✔
502
end
503

504
--- Partition a list using a classifier function.
505
-- The function may return nil, but this will be converted to the string key '<nil>'.
506
-- @func fun a function of at least one argument
507
-- @param ... will also be passed to the function
508
-- @treturn MultiMap a table where the keys are the returned values, and the values are Lists
509
-- of values where the function returned that key.
510
-- @see pl.MultiMap
511
function List:partition (fun,...)
160✔
512
    fun = function_arg(1,fun)
12✔
513
    local res = {}
8✔
514
    for i = 1,#self do
88✔
515
        local val = self[i]
80✔
516
        local klass = fun(val,...)
80✔
517
        if klass == nil then klass = '<nil>' end
80✔
518
        if not res[klass] then res[klass] = List() end
88✔
519
        res[klass]:append(val)
80✔
520
    end
521
    return setmetatable(res,Multimap)
8✔
522
end
523

524
--- return an iterator over all values.
525
function List:iter ()
160✔
526
    return iter(self)
8✔
527
end
528

529
--- Create an iterator over a sequence.
530
-- This captures the Python concept of 'sequence'.
531
-- For tables, iterates over all values with integer indices.
532
-- @param seq a sequence; a string (over characters), a table, a file object (over lines) or an iterator function
533
-- @usage for x in iterate {1,10,22,55} do io.write(x,',') end ==> 1,10,22,55
534
-- @usage for ch in iterate 'help' do do io.write(ch,' ') end ==> h e l p
535
function List.iterate(seq)
160✔
536
    if type(seq) == 'string' then
124✔
537
        local idx = 0
16✔
538
        local n = #seq
16✔
539
        local sub = string.sub
16✔
540
        return function ()
541
            idx = idx + 1
80✔
542
            if idx > n then return nil
80✔
543
            else
544
                return sub(seq,idx,idx)
64✔
545
            end
546
        end
547
    elseif type(seq) == 'table' then
108✔
548
        local idx = 0
108✔
549
        local n = #seq
108✔
550
        return function()
551
            idx = idx + 1
636✔
552
            if idx > n then return nil
636✔
553
            else
554
                return seq[idx]
528✔
555
            end
556
        end
UNCOV
557
    elseif type(seq) == 'function' then
×
UNCOV
558
        return seq
×
559
    elseif type(seq) == 'userdata' and io.type(seq) == 'file' then
×
560
        return seq:lines()
×
561
    end
562
end
563
iter = List.iterate
160✔
564

565
return List
160✔
566

STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc