Skip to content

zeros, rand, randn could infer the length parameter of incompletely parameterized StaticArrays #1303

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
mikmoore opened this issue Apr 8, 2025 · 2 comments

Comments

@mikmoore
Copy link

mikmoore commented Apr 8, 2025

From https://discourse.julialang.org/t/why-does-smatrix-allocate-in-this-case/127808.

julia> zeros(SMatrix{2,2,Float32,4}, 1)
1-element Vector{SMatrix{2, 2, Float32, 4}}:
 [0.0 0.0; 0.0 0.0]

julia> zeros(SMatrix{2,2,Float32}, 1) # container is incompletely typed
1-element Vector{SMatrix{2, 2, Float32}}:
 [0.0 0.0; 0.0 0.0]

The same behavior happens for rand, randn, and probably any others in this family. And also for the MArray type.

It seems that it should be possible for the function to infer a missing length parameter and use it for the container's type.

@thchr
Copy link
Collaborator

thchr commented Apr 9, 2025

For zeros (and ones), the reason this happens is that it falls back to a Base implementation of the kind

function $fs(::Type{T}, dims) where T
    A = Array{T}(undef, dims)
    fill!(A, $f(T))
end

where e.g., fs = :zeros and f = :zero. StaticArrays' zero implementation correctly figures out the omitted type parameters in zero, but the pre-allocated array doesn't figure it out. You could argue the implementation should be:

$fs(::Type{T}, dims) where T = fill($f(T), dims)

I don't know why it isn't: but it should probably be a fix in Julia rather than StaticArrays. It's a somewhat analogous thing for randn and randexp, but the methods are inherited from the Random stdlib (and a fill approach wouldn't work).

For rand, the methods are actually defined in StaticArrays - but those methods should probably be removed since they do the same thing as the fallback definition in Random.

@jishnub
Copy link
Member

jishnub commented Apr 18, 2025

Implementing zeros in terms of fill may not be possible in general, if the zero element isn't of the same type. To be precise, the result may not have the same eltype.

JuliaLang/julia#54767 (comment)

One (hacky) solution might be to dispatch on the zero element as well, which may then be extended elsewhere.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants