Stream: helpdesk (published)

Topic: sum with wrong keyword argument


view this post on Zulip Karl Wessel (Nov 13 2025 at 10:31):

julia> sum(i for i in 1:2, dims=(1,2))
6

julia> sum(i for i in 1:2; dims=(1,2))
ERROR: MethodError: no method matching mapfoldl(::typeof(identity), ::typeof(Base.add_sum), ::Base.Generator{…}; dims::Tuple{…})
This method does not support all of the given keyword arguments (and may not support any).

Closest candidates are:
  mapfoldl(::Any, ::Any, ::Any; init) got unsupported keyword argument "dims"
   @ Base reduce.jl:167

Stacktrace:
 [1] kwerr(::@NamedTuple{…}, ::Function, ::Function, ::Function, ::Base.Generator{…})
   @ Base ./error.jl:175
 [2] mapreduce(f::Function, op::Function, itr::Base.Generator{UnitRange{…}, typeof(identity)}; kw::@Kwargs{dims::Tuple{…}})
   @ Base ./reduce.jl:299
 [3] sum(f::Function, a::Base.Generator{UnitRange{Int64}, typeof(identity)}; kw::@Kwargs{dims::Tuple{Int64, Int64}})
   @ Base ./reduce.jl:524
 [4] sum(a::Base.Generator{UnitRange{Int64}, typeof(identity)}; kw::@Kwargs{dims::Tuple{Int64, Int64}})
   @ Base ./reduce.jl:553
 [5] top-level scope
   @ REPL[2]:1
Some type information was truncated. Use `show(err)` to see complete types.

Is this expected?

view this post on Zulip Karl Wessel (Nov 13 2025 at 10:33):

I would have expected that the first version throws the same error as the second.

view this post on Zulip Mason Protter (Nov 13 2025 at 10:39):

Yes, it's expected. There's two separate parser quirks you need to know here:

  1. for i = 1:2 is another way to write for i in 1:2 (and in fact the former is what the parser lowers to I think because Stefan always liked the = syntax more, not sure of the exact history):
julia> [x+1 for x = 1:2]
2-element Vector{Int64}:
 2
 3
  1. Julia supports multidimensional comprehensions:
julia> [(x, y) for x in 1:3, y in (:a, :b, :c)]
3×3 Matrix{Tuple{Int64, Symbol}}:
 (1, :a)  (1, :b)  (1, :c)
 (2, :a)  (2, :b)  (2, :c)
 (3, :a)  (3, :b)  (3, :c)

Putting that together, julia parses your first call as

generator = (i for i in 1:2, dims in (1,2))
sum(generator)

view this post on Zulip Karl Wessel (Nov 13 2025 at 10:49):

Ahh, I did know about multidimensional comprehension, but did not notice that it could be parsed like that. Makes sense now.

view this post on Zulip Karl Wessel (Nov 13 2025 at 10:53):

Another reason why I really should use ; instead of , to set keyword arguments :)

view this post on Zulip Mason Protter (Nov 13 2025 at 11:28):

Yep. This is really the downside of julia having so much syntax. It's always nice to add special syntax for one more thing, but it does end up creating some pretty confusing edge cases


Last updated: Nov 27 2025 at 04:44 UTC