Skip to content

replace for non-collection arguments #56578

Open
@tillfalko

Description

From the documentation:

replace(A, old_new::Pair...; [count::Integer])

Return a copy of collection A where, for each pair old=>new in old_new,
all occurrences of old are replaced by new.

Yet A is not actually constrained to collections. This seems like a wasted opportunity to use Julia's type system to prevent bugs like the following.

x = 2.2
replace(x, NaN=>0)

ERROR: MethodError: no method matching similar(::Float64, ::Type{Float64})

Possible Solutions (Discussion)

  1. Somehow restrict the methods of replace to collections. I'm not sure if this is possible as there does not seem to be an AbstractCollection that encompasses AbstractArray, AbstractSet, AbstractString, etc.
  2. Support non-collection values of A. While the example above could be done with ifelse or the ternary operator, replace could be very useful for non-iterable values of A. For example I often find myself wanting to write
    (some function)
    return replace(x, Inf=>NaN, -Inf=>NaN)
end

Metadata

Assignees

No one assigned

    Labels

    collectionsData structures holding multiple items, e.g. sets

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions