Bug in replace! function

See the following MWE:

a = "Hello World" #"Hello World"
b = replace(a,"Hello" => "Bye") #"Bye World"
replace!(a, "Hello" => "Bye") 

#ERROR: LoadError: MethodError: no method matching _replace!(::Base.var"#new#295"{Tuple{Pair{String, String}}}, ::String, ::String, ::Int64)
Closest candidates are:
  _replace!(::Union{Function, Type}, ::AbstractArray, ::AbstractArray, ::Int64) at set.jl:658
  _replace!(::Union{Function, Type}, ::Dict{K, V}, ::AbstractDict, ::Int64) where {K, V} at set.jl:691
  _replace!(::Union{Function, Type}, ::Set{T}, ::AbstractSet, ::Int64) where T at set.jl:723
  ...
Stacktrace:
 [1] replace_pairs!(res::String, A::String, count::Int64, old_new::Tuple{Pair{String, String}})
   @ Base .\set.jl:488
 [2] replace!(A::String, old_new::Pair{String, String}; count::Int64)
   @ Base .\set.jl:478
 [3] replace!(A::String, old_new::Pair{String, String})
   @ Base .\set.jl:478

So when I try to change the variable a it gives the error as stated above. It should be possible to adjust variable a with the replace! function right? Thanks for helping me out. I use julia 1.6 btw.

Your problem here is that replace! isn’t defined for strings because strings are immutable.

This is also true for other immutable collections. For example, replace!([1,2,3], 1=>2) works, but replace!(1:3, 1=>2) does not.

2 Likes

ah ok. Thanks for the reply! Is there any particular reason that strings are immutable?

Yes, immutability allows the compiler and runtime to reason about the values of string more easily and execute code more efficiently in time and space.

For space efficiency, immutable strings allow the use of variable-width encodings such as UTF-8 which store text quite compactly. If you had a mutable UTF-8 string, replace! (or other per-character mutations) would be approximately as slow as creating a whole new string anyway, because the number of bytes taken by each character isn’t fixed.

I also guess it was an intentional interface choice that the identity of a string should be defined by its value only, in the same way that numbers are.

4 Likes