Can you please tell me why this doesn't match the 2nd candidate, and what I must do to get it to work?
(Practice) julia> x
3-element StaticArraysCore.MArray{Tuple{3}, Float64, 1, 3} with indices SOneTo(3):
1.0
2.0
3.0
(Practice) julia> ones(x)
MethodError: no method matching ones(::StaticArraysCore.MArray{Tuple{3}, Float64, 1, 3})
Closest candidates are:
ones(::Tuple{Vararg{Union{Integer, AbstractUnitRange}}}) at ~/.data/asdf-vm/installs/julia/1.7.3/share/julia/base/array.jl:522
ones(::Type{StaticArraysCore.MArray{Tuple{N}, T, 1, N} where T}) where N at ~/.data/julia/packages/StaticArrays/5bAMi/src/MVector.jl:4
ones(::Type{StaticArraysCore.SArray{Tuple{N}, T, 1, N} where T}) where N at ~/.data/julia/packages/StaticArrays/5bAMi/src/SVector.jl:4
...
Unfortunately this particular method list and how it highlights on Zulip (and probably elsewhere too) makes the answer harder to find. The key is that candidates 2 and 3 match on Type{M/SArray}
instead of M/SArray
. Thus they'll match ones(typeof(x))
but not ones(x)
.
That seems rather bizarre from a user standpoint.
That means runtime type checking is necessary, correct?
as is implied with typeof
Semantically it always happens, but more often than not it is elided completely by the compiler.
e.g. if you define a function indirection(::T) where T = ones(T)
.
Hmm, ok. Though I get a "Missing reference: T" with that.
Ah nevermind. I see what I did. Thanks for the help.
I do think there's a UX argument for Type
s printing out differently in method signatures than other parametric types, but I'm not sure how reasonable/feasible that is.
Relatedly, I want to define a method analogous to isone
for 1xN matrices, that checks if all their elements are ones. This seems to break expectations to add a method on an MVector, as I'm not checking the main diagonal of a matrix. Thoughts?
or rather analagous to iszero
but defining for isone
seems wrong.
isone
is typically only used for scalars - is there anything wrong with all(isone, x)
?
and since neitherisone
nor SArray
are owned by you, defining a new isone
method for SArray
is definitely type piracy
I did isones(v::MathVector{T}) where {T} = v == ones(T)
. Notice the custom plural function name.
gotcha!
that definition seems a little wasteful, since it'll allocate the ones(T)
vector too, for comparison
Yeah I realize that. I'm iteratively trying to make everything I write better as I read the Base/stdlib module docs, but if you have any suggestions, I'm all ears.
all(isone, x)
Ah I missed that. Thanks!
Michael Fiano has marked this topic as resolved.
Last updated: Nov 06 2024 at 04:40 UTC