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