Skip to content

Problems of the current map function #4466

@lindahua

Description

@lindahua

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions