-
Notifications
You must be signed in to change notification settings - Fork 0
/
dynamic_lists.wil
100 lines (74 loc) · 1.91 KB
/
dynamic_lists.wil
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
/*
Wilfrid features built-in dynamic lists.
They can hold any type.
*/
fn main ()
{
/*
To declare a dynamic list, we use square brackets,
like in the case of an array but without a size provided.
*/
let int_list := new int[]
/*
A dynamic list can hold any type.
*/
let things_list := new thing[]
/*
Adding new elements:
*/
int_list.add(1)
things_list.add({ 10, 20 } as thing)
/*
Checking the list's state:
*/
let capacity = int_list.capacity()
let length = int_list.length()
printf("The int list total count is %d\\n", length)
printf("The int list total capacity is %d\\n", capacity)
/*
A dynamic list is implemented as an array with a fixed
size plus some metadata. The underlying array is
reallocated each time the capacity is filled.
Despite reallocation, pointers to dynamic lists are stable.
Therefore it's safe to keep references to them.
*/
for (let i := 0, i < 30, i++)
{
int_list.add(i + 2)
}
printf("The int list total count is %d\\n", int_list.length())
printf("The int list total capacity is %d\\n", int_list.capacity())
/*
Lists elements can be accessed the same as arrays:
*/
int_list[0] = 0
int_list[1] = int_list[1] + 100
int_list[2] = int_list[1]
/*
Using the length method, we can iterate over a list
in a for loop:
*/
printf("Printing the int list:\\n")
for (let i := 0, i < int_list.length(), i++)
{
let value = int_list[i]
printf("%d ", value)
}
printf("\\n")
/*
To free a list, we use the 'delete' statement:
*/
delete int_list
delete things_list
/*
As with every other object, lists can be allocated
with 'auto' which means that they will be automatically
garbage-collected when they are no longer used.
*/
let other_list = auto thing[]
}
struct thing
{
value: long,
other_value: ulong
}