Why no mutating filter function for strings?

Is there a reason why

julia> str = " a"
" a"

julia> filter(isspace, str)
" "

works but

julia> filter!(isspace, str)
ERROR: MethodError: no method matching filter!(::typeof(isspace), ::String)
Closest candidates are:
  filter!(::Any, ::AbstractArray{T,1} where T) at array.jl:2503
  filter!(::Any, ::IdDict) at iddict.jl:162
  filter!(::Any, ::Dict{K,V}) where {K, V} at dict.jl:686
  ...
Stacktrace:
 [1] top-level scope at REPL[3]:1

doesn’t? Why there isn’t a mutating form of filter for strings?

This is probably because strings are immutable. Methods with ! work by modifying the container passed to them, but you can’t modify a string in Julia (for performance reasons).

2 Likes

Putting 2 and 2 together, I realise that other functions return SubStrings.

Though I just end up using str = filter(..., str) anyway, changing the original variable.

Though I’m surprised that there’s no equivalent of push! and deleteat!. I’ll read up more on this.

Thanks!

1 Like

You could always make an issue asking for this feature. That said, one critical difference between a function like filter and a function like findfirst is that the latter always returns a result which can be described by a single start and end index, while the former can require extensive auxiliary space to store the result (e.g. filter(x->x=='0', "0110010101010") )

1 Like

What would they do on an immutable object?

Sorry, I’m coming across wrong. I’m new to Julia and am learning why the design of the language is in certain ways. My asking was not an expectation of conformation to a structure, but an inquiry for better understanding, challenging my intuition. I couldn’t find anything in the documentation explaining, so I thought I’d ask.

Throw an error I suppose.

Again, not expecting a change from my question. Just looking for understanding, and strings being immutable for performance makes sense. Thanks!

But they already do, eg

julia> push!("I am immutable", 'q')
ERROR: MethodError: no method matching push!(::String, ::Char)
1 Like

And likewise for filter! as per my original post, yes.

I was thinking an error that mentions an inappropriate attempt to mutate an immutable object, rather than no method defined for that combination of input variable types.

A post was split to a new topic: Why are Julia strings immutable?