Skip to content
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

reduce and foldr/foldl are inconsistent for + and empty vectors #20144

Closed
dlfivefifty opened this issue Jan 20, 2017 · 5 comments
Closed

reduce and foldr/foldl are inconsistent for + and empty vectors #20144

dlfivefifty opened this issue Jan 20, 2017 · 5 comments

Comments

@dlfivefifty
Copy link
Contributor

In 0.6, reduce and foldr/foldl are inconsistent for empty vectors:

julia> reduce(+,Float64[])
0.0

julia> foldr(+,Float64[])
ERROR: BoundsError: attempt to access 0-element Array{Float64,1} at index [0]
Stacktrace:
 [1] foldr(::Function, ::Array{Float64,1}) at ./reduce.jl:160

julia> foldl(+,Float64[])
0.0
@dlfivefifty
Copy link
Contributor Author

Related issue is #5797 (comment)

@vsartor
Copy link

vsartor commented Jan 20, 2017

I'm new to Julia so take all of this with a grain of salt.

So the foldr with two arguments (here) is calling mapfoldr with three arguments (here).

It's defined as
mapfoldr(f, op, itr) = (i = endof(itr); mapfoldr_impl(f, op, f(itr[i]), itr, i-1))

So not only would it send -1 as the i argument to mapfoldr_impl, it also tries to apply the function to itr[i], which is the 0-index access that happened here.

I think the check for i == 0 in mapfoldr_impl should (also?) happen before the call, since to pass the v0 argument, it needs to access a member of the array (which in this case is impossible).

reduce and foldl seem to use mapfoldl, which does the proposed check (here).

Should be an easy fix if I'm right.

@vsartor
Copy link

vsartor commented Jan 20, 2017

So, the check on foldl/reduce was added as a fix for #7465, but it wasn't added to foldr, so I think it really is intended for a check to exist in mapfoldr for empty arguments.

I'm gonna go ahead and work on a PR if that's okay.

Sacha0 pushed a commit that referenced this issue Jan 27, 2017
Fix behavior of foldr on empty arrays

When foldr is called with two arguments and an empty array, mapfoldr does not make a check for empty array and tries to access the first element. This check is present in mapfoldl.
@vsartor
Copy link

vsartor commented Jan 28, 2017

This issue should be closed (see #20160).

@Sacha0
Copy link
Member

Sacha0 commented Jan 28, 2017

Thanks @Vsart!

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