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

Problems of the current map function #4466

Closed
lindahua opened this issue Oct 10, 2013 · 4 comments
Closed

Problems of the current map function #4466

lindahua opened this issue Oct 10, 2013 · 4 comments

Comments

@lindahua
Copy link
Contributor

Current implementation relies on the result evaluated on the first item to determine the element type of the result array. This approach is problematic when the type of the evaluated result may vary. Here is an example

julia> map(+, {1, 1.1}, [1, 1])
ERROR: InexactError()
 in setindex! at array.jl:410
 in map_to2 at abstractarray.jl:1624
 in map at abstractarray.jl:1636

However, on the other hand, list comprehension has the magic to correctly infer the result type:

julia> x = {1, 1.1};
julia> y = [1, 1];
julia> [x[i]+y[i] for i = 1:2]
2-element Array{Any,1}:
 2  
 2.1

This suggests a probably more correct way to implement the map function, that is, based on the list comprehension, as follows

function my_map(f, a, b)
    s = promote_shape(size(a), size(b)) 
    [f(a[i], b[i]) for i = 1 : prod(s)]
end

julia> my_map(+, x, y)
2-element Array{Any,1}:
 2  
 2.1

Clearly, my_map correctly handles the result type variation. Why not we use this implementation?

@lindahua
Copy link
Contributor Author

Oh, I should add a reshape statement in my_map above to restore the correct shape.

@simonster
Copy link
Member

Julia can't presently specialize on function arguments, so I think that comprehension will always make a Vector{Any}:

julia> my_map(+, [1, 2, 3], [4, 5, 6])
3-element Array{Any,1}:
 5
 7
 9

@JeffBezanson
Copy link
Member

Mostly a dup of #210.

@lindahua
Copy link
Contributor Author

I see. Thanks. Let's revisit this when return type inference facility is available.

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