Open
Description
This is because the default sum
method passes the init
kwarg, and defining the specialized method for an array that only accepts dims
doesn't allow the fallback to the generic method that accepts init
. This is particularly bad because the docstring of sum
mentions the method sum(f, A::AbstractArray; dims)
, which seems to suggest that one may specialize this method for their own array types. There should be some guidelines on which sum
method to define.
MWE
julia> struct MyFillArr{T} <: AbstractVector{T}
val :: T
len :: Int
end
julia> Base.size(M::MyFillArr) = (M.len,)
julia> Base.getindex(M::MyFillArr, i::Int) = (checkbounds(M, i); M.val)
julia> sum(MyFillArr(false, 4))
0
julia> Base.sum(f, M::MyFillArr; dims=:) = sum(f, collect(M); dims)
julia> sum(MyFillArr(false, 4))
ERROR: MethodError: no method matching sum(::Base.var"#361#362"{typeof(identity)}, ::MyFillArr{Bool}; init::Int64)
This error has been manually thrown, explicitly, so the method may exist but be intentionally marked as unimplemented.
Closest candidates are:
sum(::Any, ::MyFillArr; dims) got unsupported keyword argument "init"
@ Main REPL[5]:1
sum(::Any, ::AbstractArray; dims, kw...)
@ Base reducedim.jl:981
sum(::Any, ::Any; kw...)
@ Base reduce.jl:532
...
Stacktrace:
[1] kwerr(::@NamedTuple{init::Int64}, ::Function, ::Function, ::MyFillArr{Bool})
@ Base ./error.jl:165
[2] _simple_count(pred::Function, itr::MyFillArr{Bool}, init::Int64)
@ Base ./reduce.jl:1377
[3] _count(f::Function, A::MyFillArr{Bool}, dims::Colon, init::Int64)
@ Base ./reducedim.jl:412
[4] count
@ ./reducedim.jl:410 [inlined]
[5] count(A::MyFillArr{Bool}; dims::Function, init::Int64)
@ Base ./reducedim.jl:409
[6] sum(a::MyFillArr{Bool}; kw::@Kwargs{})
@ Base ./reduce.jl:562
[7] top-level scope
@ REPL[6]:1
julia> versioninfo()
Julia Version 1.11.0-rc2
Commit 34c3a63147b (2024-07-29 06:24 UTC)
Build Info:
Official https://julialang.org/ release
Platform Info:
OS: Linux (x86_64-linux-gnu)
CPU: 12 × Intel(R) Core(TM) i7-10750H CPU @ 2.60GHz
WORD_SIZE: 64
LLVM: libLLVM-16.0.6 (ORCJIT, skylake)
Threads: 1 default, 0 interactive, 1 GC (on 12 virtual cores)
Environment:
JULIA_EDITOR = subl