Skip to content

Inplace mask of vector #39470

Closed
Closed
@MasonProtter

Description

@MasonProtter

It was recently asked on Slack if there is an inplace equivalent of my_vector = my_vector[my_mask], where we assume that the user already needs the mask and does not want to essentially recompute it with filter!. I took a glance at the implementation of filter! in Base and saw that it could be easily adapted to this use-case:

function mask!(a::AbstractVector, m::AbstractVector{Bool})
    j = firstindex(a)
    for i in eachindex(a, m)
        @inbounds begin
            ai = a[i]
            mi = m[i]
            a[j] = ai
        end
        j = ifelse(mi, nextind(a, j), j)
    end
    j > lastindex(a) && return a
    if a isa Vector
        resize!(a, j-1)
        sizehint!(a, j-1)
    else
        deleteat!(a, j:lastindex(a))
    end
    return a
end

julia> let a = [:a, :b, :c], m = [true, false, true]
           mask!(a, m)
       end
2-element Vector{Symbol}:
 :a
 :c

Is this something that would be worth putting in Base? If so, I can whip up a PR, but don't want to waste my time if it's something that's already been discussed. I tried searching around but didn't find anything, but perhaps I missed a discussion.

Metadata

Metadata

Assignees

No one assigned

    Labels

    arrays[a, r, r, a, y, s]

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions