OILS / stdlib / ysh / list.ysh View on Github | oilshell.org

62 lines, 45 significant
1func any(list) {
2 ### Returns true if any value in the list is truthy.
3 # Empty list: returns false
4
5 for item in (list) {
6 if (item) {
7 return (true)
8 }
9 }
10 return (false)
11}
12
13func all(list) {
14 ## Returns true if all values in the list are truthy.
15 # Empty list: returns true
16
17 for item in (list) {
18 if (not item) {
19 return (false)
20 }
21 }
22 return (true)
23}
24
25func sum(list; start=0) {
26 ### Returns the sum of all elements in the list.
27 # Empty list: returns 0
28
29 var sum = start
30 for item in (list) {
31 setvar sum += item
32 }
33 return (sum)
34}
35
36func repeat(x, n) {
37 ### Returns a list with the given string or list repeated
38
39 # Like Python's 'foo'*3 or ['foo', 'bar']*3
40 # negative numbers are like 0 in Python
41
42 var t = type(x)
43 case (t) {
44 Str {
45 var parts = []
46 for i in (0 .. n) {
47 call parts->append(x)
48 }
49 return (join(parts))
50 }
51 List {
52 var result = []
53 for i in (0 .. n) {
54 call result->extend(x)
55 }
56 return (result)
57 }
58 (else) {
59 error "Expected Str or List, got $t"
60 }
61 }
62}