This is NOT to complain about Julia, rather a learning experience, so bear with me…
Dispatching to a struct type seems like the match of the last resort - after a lot of not this, not that, not really testable. And contrary to Sudoku, one never knows if it can be solved.
I got great help here putting multiple dispatch to work, still think a test if an object is a structure is necessary.
The following serializer code iterates through an object’s hierarchy and whenever it sees homogeneous data, writes it out. The prefixes with type and dimension data are omitted here.
I feel this can be made better.
function isstruct(v)
if applicable(fieldnames, typeof(v))
(fieldcount(typeof(v)) > 0) && !(typeof(v)<:Tuple) # for Array_of_Any
else
false
end
end
Writables = Union{<:Real, Char, String,
AbstractArray{<:Real},
AbstractArray{Char},
AbstractArray{String}}
function serial(v)
tv = typeof(v)
if tv <: Writables
println(v)
println("---")
elseif isstruct(v)
println("(Struct)")
for name in fieldnames(tv)
println("$(name)")
serial(getfield(v, name));
end
elseif tv<:AbstractArray || tv <: Tuple
println("(Array/Tuple)")
v1 = first(v)
if isstruct(v1)
println("(Struct)")
for name in fieldnames(typeof(v1))
println("$(name)")
serial(getfield.(v, name));
end
# todo: array of homogeneous tuple
else
serial.(v);
end
else
error("unknown type: $tv")
end
end
# Test data
Array_of_Int = [1 ,2]
Array_of_Tuple = [(1, 2), (2, 3)]
Array_of_Any = [(1, 2), "Ab"]
mutable struct Coords
x::Float64
y::Float64
z::Float64
end
Coords() = Coords(rand(), rand(), rand())
Array_of_Struct = [Coords() for i in 1:5]
Single_Struct = Coords()
# Test
println("Test Array_of_Int")
serial(Array_of_Int)
println()
println("Test Array_of_Tuple")
serial(Array_of_Tuple)
println()
println("Test Array_of_Any")
serial(Array_of_Any)
println()
println("Test Single_Struct")
serial(Single_Struct)
println()
println("Test Array_of_Struct")
serial(Array_of_Struct)
Output:
Test Array_of_Int
[1, 2]
---
Test Array_of_Tuple
(Array/Tuple)
(Array/Tuple)
1
---
2
---
(Array/Tuple)
2
---
3
---
Test Array_of_Any
(Array/Tuple)
(Array/Tuple)
1
---
2
---
Ab
---
Test Single_Struct
(Struct)
x
0.9220727028581359
---
y
0.6295692430403457
---
z
0.023560089621190716
---
Test Array_of_Struct
(Array/Tuple)
(Struct)
x
[0.834535060962323, 0.340497217736315, 0.7824763128066028, 0.8189685607684121, 0.9859094096185965]
---
y
[0.4761584369317642, 0.4352515300190545, 0.14527270184939045, 0.6024455919678469, 0.6632760955815888]
---
z
[0.28120117129446975, 0.19801990106458578, 0.03265890208397537, 0.6550273380547817, 0.04383975637217996]
---