Method of `mapreduce` with multiple arguments

question

#1

I haven’t been able to find a method for mapreduce accepting several collections as arguments. For map, such methods exist, e.g.

julia> map(+, [1,2], [3,4])
2-element Array{Int64,1}:
 4
 6

I would like to use something as mapreduce(f, op, cs...), e.g. an equivalent to

julia> reduce(+, map((x,y)->abs2(x-y), [1,2], [3,4]))
8

using mapreduce and avoiding the temporary array. I know that there are some problems with the optional argument v0 of mapreduce(f, op, vo, itr).

However, I would like to know whether such functionality exists or might be wanted.


#2

How about

julia> mapreduce(x -> abs2(x[1] - x[2]), +, zip([1, 2], [3, 4]))
8

#3

Thank you very much for your answer!

Some benchmarks to compare:

julia> using BenchmarkTools

julia> N=10^4; x=Vector(linspace(0,1,N)); y=Vector(logspace(0,1,N));

julia> f1(x,y) = reduce(+, map((x,y)->abs2(x-y), x, y))
f1 (generic function with 1 method)

julia> f2(x,y) = mapreduce(x -> abs2(x[1] - x[2]), +, zip(x, y))
f2 (generic function with 1 method)

julia> f3(x,y) = norm(x-y)^2
f3 (generic function with 1 method)

julia> f4(x,y) = sum(abs2, x-y)
f4 (generic function with 1 method)

julia> @btime $f1($x, $y)
  17.134 μs (4 allocations: 78.25 KiB)
165424.77420828358

julia> @btime $f2($x, $y)
  9.777 μs (4 allocations: 96 bytes)
165424.77420828363

julia> @btime $f3($x, $y)
  10.262 μs (2 allocations: 78.20 KiB)
165424.77420828355

julia> @btime $f4($x, $y)
  9.215 μs (2 allocations: 78.20 KiB)
165424.7742082836

And finally:

julia> function f5(x::AbstractVector, y::AbstractVector)
           @assert length(x) == length(y)
           s = zero(abs2(x[1] - y[1]))
           @inbounds for i in eachindex(x)
               s += abs2(x[i]-y[i])
           end
           s
       end
f5 (generic function with 2 methods)

julia> @btime $f5($x, $y)
  7.707 μs (0 allocations: 0 bytes)
165424.77420828363