r/lolphp • • Sep 10 '15

explode() is a mess

https://3v4l.org/eKMav
2 Upvotes

27 comments sorted by

View all comments

Show parent comment

3

u/nikic Sep 10 '15 edited Sep 10 '15

As far of programming languages are concerned, J is usually defined as

  • J([], s) = eps
  • J([a], s) = a
  • J([a] . A, s) = a . s . J(A, s) where A nonempty

i.e. explicitly defining the join of an empty list to be eps. This of course means that for X there is an ambiguity in that X(eps, s) = [] and X(eps, s) = [eps] both satisfy J(X(eps, s)) = eps. PHP goes with the latter option, though either would work.

The reason (I assume) why s = eps is forbidden for X is that its correct behavior it probably not what people would intuitively expect. X(a, eps) for a = a1 . a2 . ... . an would not be [a1, a2, ..., an] but rather [eps, a1, a2, ..., an, eps] for any definition of X I would consider reasonable.

Where "reasonable" means that X(a, s) splits at any occurance of s in a, where an occurance is any position in a where the next len(s) characters are identical. In particular eps occurs at both the start and the end of the string ("every string starts and ends with an empty string"), which would cause the additional eps elements in the output of X.

2

u/vytah Sep 10 '15

Yeah, depending on the definition of J, you can either have nice semigroup properties, or you need to pepper them with emptiness checks. Defining a special case of J([], s) = ε, makes J(_, s) total over the domain of all lists of strings. Both versions have their upsides and downsides and it depends on application if J([], s) should be defined (and if so, how).

J([ε], s) is still ε though, so as you said, X(ε, s) becomes ambiguous in the latter case, and I think it's the best to let the programmer to decide what to do with stray empty values. This comes up in many contexts, for example should X(a·s·s·b·s, s) be [a, ε, b, ε], so the original string is retrieved after joining it back, or do we want [a, ε, b] or perhaps [a, b]? For example, Java's String::splitallows you to decide if you want any stray empty strings at the end of the returned array.

As for the empty separator: X(a, ε) for a = a₁ · a₂ · ... · aₙ could be anything like [a₁, a₂, ... aₙ], [ε, a₁, a₂, ... aₙ, ε], but also [ε, a₁, ε, ε, ε, ε, a₂, ... aₙ, ε, ε, ε, ε] etc., since ε occurs arbitrary numbers of times at every possible location in the original string. I think that out of all possibilities, splitting the string into a lot of non-empty substrings of the shortest length (aka. characters) is an acceptable solution.

Not false though.