Skip to content

Commit 85e9590

Browse files
committed
uniformize CartesianSpace constructor
1 parent 8d63119 commit 85e9590

File tree

1 file changed

+19
-18
lines changed

1 file changed

+19
-18
lines changed

src/spaces/cartesianspace.jl

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,26 +12,27 @@ vector space that is implicitly assumed in most of matrix algebra.
1212
struct CartesianSpace <: ElementarySpace
1313
d::Int
1414
end
15+
1516
CartesianSpace(d::Integer = 0; dual = false) = CartesianSpace(Int(d))
16-
function CartesianSpace(dim::Pair; dual = false)
17-
if dim.first === Trivial()
18-
return CartesianSpace(dim.second; dual = dual)
19-
else
20-
msg = "$(dim) is not a valid dimension for CartesianSpace"
21-
throw(SectorMismatch(msg))
22-
end
23-
end
24-
function CartesianSpace(dims::AbstractDict; kwargs...)
25-
if length(dims) == 0
26-
return CartesianSpace(0; kwargs...)
27-
elseif length(dims) == 1
28-
return CartesianSpace(first(dims); kwargs...)
29-
else
30-
msg = "$(dims) is not a valid dimension dictionary for CartesianSpace"
31-
throw(SectorMismatch(msg))
32-
end
17+
CartesianSpace(dim::Pair; kwargs...) = CartesianSpace((dim,); kwargs...)
18+
function CartesianSpace(dims; dual::Bool = false)
19+
# using manual iteration here to avoid depending on `length` while still checking it is
20+
# 0 ≤ length ≤ 1
21+
next = Base.iterate(dims)
22+
isnothing(next) && return CartesianSpace(0)
23+
24+
(c, d), state = next
25+
convert(Trivial, c) === Trivial() ||
26+
throw(SectorMismatch(lazy"$c is not a valid charge for CartesianSpace"))
27+
28+
V = CartesianSpace(d)
29+
30+
next = Base.iterate(dims, state)
31+
isnothing(next) ||
32+
throw(SectorMismatch(lazy"$dims is not a valid dimension iterable for CartesianSpace"))
33+
34+
return V
3335
end
34-
CartesianSpace(g::Base.Generator; kwargs...) = CartesianSpace(g...; kwargs...)
3536

3637
# convenience constructor
3738
Base.getindex(::RealNumbers) = CartesianSpace

0 commit comments

Comments
 (0)