Line data Source code
1 : #
2 : # General helpers: I'm missing these in the standard library!
3 : #
4 : if VERSION < v"1.7"
5 : export findmin, argmin, findmax, argmax
6 :
7 0 : Base.findmin(f::Base.Generator) = mapreduce(reverse, min, enumerate(f))
8 0 : Base.argmin(f::Base.Generator) = findmin(f)[2]
9 :
10 0 : Base.findmax(f::Base.Generator) = mapreduce(reverse, max, enumerate(f))
11 0 : Base.argmax(f::Base.Generator) = findmax(f)[2]
12 : end
13 :
14 : #-----------------------------------------------------------------------------
15 :
16 : """
17 : d = struct_to_dict(s)
18 :
19 : Convert `struct` type (or named tuple) to `Dict`.
20 :
21 : One use case is testing implementations of `Base.copy` for a new
22 : `struct`: There is a generic equal comparison for `Dict`, and we can
23 : easily check that no fields where missed.
24 : """
25 0 : function struct_to_dict(s)
26 0 : Dict(key => getfield(s, key) for key in propertynames(s))
27 : end
28 :
29 : # NOTE: https://stackoverflow.com/questions/68852523/julia-struct-to-dict
30 :
31 : #-----------------------------------------------------------------------------
32 :
33 0 : decompose_vectype(v::AbstractVector{T}) where {T} = length(v), T
34 :
35 0 : decompose_vectype(::SVector{N, T}) where {N, T} = (N, T)
36 :
37 : """
38 : N, T = decompose_vectype(v)
39 :
40 : Get `eltype` and `length` from `v::AbstractVector`. The intended use
41 : is decomposing parameters of `SVector{N,T}` (at no cost).
42 : """ decompose_vectype
43 :
44 0 : function filled(::Type{SVector{N, T}}, xs...; fill) where {N, T}
45 0 : SVector(T.(xs)..., ntuple(_ -> T(fill), N-length(xs))...)
46 : end
47 :
48 0 : filled(x::SVector, xs...; fill) = filled(typeof(x), xs...; fill)
49 :
50 : """
51 : x = SVector(...)
52 : y = filled(typeof(x), [y1, y2, ...], fill=yend)
53 : y = filled(x, [y1, y2, ...], fill=yend)
54 :
55 : Construct an `SVector{T, N}` as given by `typeof(x)` with components
56 : `(y1, y2, ..., yend, ..., yend)`, i.e., set the first components and
57 : "fills" to match length `N`.
58 : """ filled
|