3 ms·
While an empty substring is a substring of every string, attempting to find its index in any string must signal an error, because there is no univocal value of
by adrian_b 3y ago
While an empty substring is a substring of every string, attempting to find its index in any string must signal an error, because there is no univocal value of such an index (all possible index values are equally valid answers).
On the other hand, a predicate that tests whether an empty substring is found in a string must indeed return "true".
In a function that must return a single value, an error must be signaled both when there is no value that can be returned and when there are multiple values that could be returned.
If the index of the substring is defined as the smallest such index, which makes it unique even for multiple substring occurrences, then the search function must return 0 or 1 for an empty substring, whichever is defined to be the first index.
Attempting to search an empty string for non-empty or empty substrings should always signal an error, because there are no valid index values that could be returned.
- fasterik 3y agoYeah, I think the convention should be to return the smallest valid index such that the predicate is satisfied, or an error value if the predicate isn't satisfied. As you point out, it's the same as when a non-empty string appears multiple times in a given string. So I think 0 is the only reasonable result in this case, assuming 0-based indexing.
- deleted 3y ago[deleted]
- hermitcrab 3y ago>While an empty substring is a substring of every string, attempting to find its index in any string must signal an error, because there is no univocal value of such an index (all possible index values are equally valid answers). The operations in question are to find the first (IndexOf) and last (LastIndexOf) indexes. So if the empty exists at every index, you just return the first or last one. >Attempting to search an empty string for non-empty or empty substrings should always signal an error I believe that an empty string is valid input for each parameter and should return 'not found' in some form, rather than an error. It is splitting hairs a bit though.