Mon, 18 Nov 2019 11:31:40 -0500
Add write_log to LinkedLists
| 0 | 1 | ################################# |
| 2 | # Tools for working with structs | |
| 3 | ################################# | |
| 4 | ||
| 5 | module StructTools | |
| 6 | ||
| 7 | ############## | |
| 8 | # Our exports | |
| 9 | ############## | |
| 10 | ||
| 11 | export replace, | |
| 12 | IterableStruct | |
| 13 | ||
| 14 | ###################################################### | |
| 15 | # Replace entries by those given as keyword arguments | |
| 16 | ###################################################### | |
| 17 | ||
| 18 | function replace(base::T; kw...) where T | |
| 19 | k = keys(kw) | |
| 20 | T([n ∈ k ? kw[n] : getfield(base, n) for n ∈ fieldnames(T)]...) | |
| 21 | end | |
| 22 | ||
| 23 | ######################################################### | |
| 24 | # Iteration of structs. | |
| 25 | # One only needs to make them instance of IterableStruct | |
| 26 | ######################################################### | |
| 27 | ||
| 28 | abstract type IterableStruct end | |
| 29 | ||
| 30 | function Base.iterate(s::T) where T <: IterableStruct | |
| 31 | return Base.iterate(s, (0, fieldnames(T))) | |
| 32 | end | |
| 33 | ||
| 34 | function Base.iterate( | |
| 35 | s::T, st::Tuple{Integer,NTuple{N,Symbol}} | |
| 36 | ) where T <: IterableStruct where N | |
| 37 | (i, k)=st | |
| 38 | return (i<N ? (getfield(s, i+1), (i+1, k)) : nothing) | |
| 39 | end | |
| 40 | ||
| 41 | end |