|
1 #################################################################### |
|
2 # Immutable linked list (different from the mutable lists of |
|
3 # https://github.com/ChrisRackauckas/LinkedLists.jl) |
|
4 #################################################################### |
|
5 |
|
6 module LinkedLists |
|
7 |
|
8 ############## |
|
9 # Our exports |
|
10 ############## |
|
11 |
|
12 export LinkedListEntry, |
|
13 LinkedList, |
|
14 unfold_linked_list |
|
15 |
|
16 ############# |
|
17 # Data types |
|
18 ############# |
|
19 |
|
20 struct LinkedListEntry{T} |
|
21 value :: T |
|
22 next :: Union{LinkedListEntry{T},Nothing} |
|
23 end |
|
24 |
|
25 LinkedList{T} = Union{LinkedListEntry{T},Nothing} |
|
26 |
|
27 ############ |
|
28 # Functions |
|
29 ############ |
|
30 |
|
31 function Base.iterate(list::LinkedList{T}) where T |
|
32 return Base.iterate(list, list) |
|
33 end |
|
34 |
|
35 function Base.iterate(list::LinkedList{T}, tail::Nothing) where T |
|
36 return nothing |
|
37 end |
|
38 |
|
39 function Base.iterate(list::LinkedList{T}, tail::LinkedListEntry{T}) where T |
|
40 return tail.value, tail.next |
|
41 end |
|
42 |
|
43 # Return the items in the list with the tail first |
|
44 function unfold_linked_list(list::LinkedList{T}) where T |
|
45 res = [] |
|
46 for value ∈ list |
|
47 push!(res, value) |
|
48 end |
|
49 return reverse(res) |
|
50 end |
|
51 |
|
52 end |