Very fun. What should the behaviour be if one does "ab" \ "cd"? The only reasonable thing seems to be to throw and error, which makes me wonder how much utility this’d really have.
That said, if we also supported division by a Regex, that’d actually make this thing quite a cute and occasionally useful pattern
Python has str.removeprefix and str.removesuffix which are similar.
Signature: str.removeprefix(self, prefix, /)
Docstring:
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):].
Otherwise, return a copy of the original string.
Signature: str.removesuffix(self, suffix, /)
Docstring:
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty,
return string[:-len(suffix)]. Otherwise, return a copy of the original
string.
Except that these don’t throw an error if the prefix/suffix aren’t present. A more natural analogue in Julia might be to add more optional arguments to chop, e.g. chop(s, prefix="foo", suffix="bar"). Julia already has the functions chopprefix and chopsuffix for this.
I don’t work with strings much, but I have found myself in a few situations before where I’ve done things like
if endswith(path, ".jl")
path[begin:end-3]
end
could instead be
if endswith(path, ".jl")
path / ".jl"
end
That’s a really simple example, but I’ve found a few times when writing string macros, that there’s often prefixes or suffixes I know are there that I want to chop off.
Like the idea about regex and just checked that regular languages are closed under union, intersection, complement and concatenation. Thus one could indeed define difference as
\(ra::Regex, rb::Regex) = !rb ∩ ra
with ! and ∩ being complement and intersection respectively. Not sure if this efficient in general though?
Interestingly, \ is not defined on sets as difference either – the fallback method is applicable, but fails.
Was proposed and declined in Julia#13411. There’s also the consideration that / could alternatively represent path concatenation (also declined in Julia#9488).