Tue, 07 Dec 2021 11:41:07 +0200
New logger and iteration interface
0 | 1 | #################################################################### |
3 | 2 | # Immutable linked lists (different from the mutable lists of |
0 | 3 | # https://github.com/ChrisRackauckas/LinkedLists.jl) |
4 | #################################################################### | |
5 | ||
4
59fd17a3cea0
Add __precompile__() for what it is worth
Tuomo Valkonen <tuomov@iki.fi>
parents:
3
diff
changeset
|
6 | __precompile__() |
59fd17a3cea0
Add __precompile__() for what it is worth
Tuomo Valkonen <tuomov@iki.fi>
parents:
3
diff
changeset
|
7 | |
0 | 8 | module LinkedLists |
9 | ||
3 | 10 | using DelimitedFiles |
11 | ||
12 | using ..StructTools | |
13 | ||
0 | 14 | ############## |
15 | # Our exports | |
16 | ############## | |
17 | ||
18 | export LinkedListEntry, | |
19 | LinkedList, | |
3 | 20 | unfold_linked_list, |
21 | write_log | |
0 | 22 | |
23 | ############# | |
24 | # Data types | |
25 | ############# | |
26 | ||
27 | struct LinkedListEntry{T} | |
28 | value :: T | |
29 | next :: Union{LinkedListEntry{T},Nothing} | |
30 | end | |
31 | ||
32 | LinkedList{T} = Union{LinkedListEntry{T},Nothing} | |
33 | ||
34 | ############ | |
35 | # Functions | |
36 | ############ | |
37 | ||
38 | function Base.iterate(list::LinkedList{T}) where T | |
39 | return Base.iterate(list, list) | |
40 | end | |
41 | ||
42 | function Base.iterate(list::LinkedList{T}, tail::Nothing) where T | |
43 | return nothing | |
44 | end | |
45 | ||
46 | function Base.iterate(list::LinkedList{T}, tail::LinkedListEntry{T}) where T | |
47 | return tail.value, tail.next | |
48 | end | |
49 | ||
50 | # Return the items in the list with the tail first | |
51 | function unfold_linked_list(list::LinkedList{T}) where T | |
52 | res = [] | |
53 | for value ∈ list | |
54 | push!(res, value) | |
55 | end | |
56 | return reverse(res) | |
57 | end | |
58 | ||
3 | 59 | # Write out a a “log” of LinkedList of IterableStructs as a delimited file |
60 | function write_log(filename::String, log::LinkedList{T}, comment::String) where T <: IterableStruct | |
61 | open(filename, "w") do io | |
62 | print(io, comment) | |
63 | writedlm(io, [String.(fieldnames(T))]) | |
64 | writedlm(io, unfold_linked_list(log)) | |
65 | end | |
0 | 66 | end |
3 | 67 | |
68 | end |