Division for Strings

Just had this silly idea when trying to prepend a string to an existing one. When appending, one can do:

a  = "1"
a *= ",2" # "1,2"

Now, we could use division for prepending:

a  = "1"
a /= "0," # "0,1"

What do you think? Is this any good?

/ doesn’t hold general rule that:

a *= ",2"  
# same as
a = a * ",2"

instead you get:

a /= "0,"  
# same as
a = "0," * a

If we give division a meaning for strings, it’d likely be one that’s compatible with whatever * means for strings: https://github.com/JuliaLang/julia/pull/13411. In other words, it’d remove common subsequences in contrast to how * appends subsequences.

7 Likes

I still don’t entirely hate that. It should error if the prefix/suffix doesn’t match.

Why not use

a = "1"
a =* "0."  # same as a = "0." * a

This way you can have consistency

Because there is no =*. There is no *= either in the sense of having a primitive, it just expands to * and assignment. Eg

julia> Meta.@lower a *= 1
:($(Expr(:thunk, CodeInfo(
    @ none within `top-level scope'
1 ─ %1 = a * 1
│        a = %1
└──      return %1
))))

Being able to prepend a string in this way is very useful but division is entirely the wrong operator for the functionality. It’s easy enough to try out in your own code though.

julia> Base.:/(a::AbstractString, b::AbstractString) = b * a

julia> a = "a"
"a"

julia> a /= "b"
"ba"