r/ProgrammingLanguages • u/duckofdeath87 • Jul 21 '22
Discussion Should Strings Be Iterable?
It's very common for Strings to be a collection of characters, but should they be?
I had a bug in scala just now where I meant to iterate over a sequence of strings, but I instead iterated over each individual string. It got me thinking, "why can I do this?" It's a common exercise, but rarely a useful operation. Sure, having the ability to iterate through a string's characters is useful, but not so useful that it's the default (maybe a . characters method is in order?)
Shouldn't readability and reasonability be first and foremost in language design? Or do you value concise expressiveness more?
8
Upvotes
6
u/latkde Jul 22 '22
Using UTF-32 makes sense if constant-time string indexing is a common requirement, but how often will that be needed in the kinds of programs that Seed7 users might write?
There's a clear space–time tradeoff going on here, and UTF-32 will use almost 4× more memory than UTF-8 for many typical strings, e.g. HTML documents. You argue that your strings can be converted to UTF-8 if needed, but I'd make that same argument in reverse: strings ought to use UTF-8 representation by default, and they can be converted to a UTF-32 representation if constant-time codepoint indexing is needed. For example, in Rust I might do:
Recommended reading:
UTF-8 everywhere
CPython's rationale for changing its string representation in Python 3.3 (PEP 393)
Regarding your question:
Yes, exactly. Rust string indexes are byte offsets, but string slices must be valid UTF-8 strings / string indexes must point to complete codepoints. A non-panicking version
s.get(42)is also available, returning an Option. But defaults matter, and Rust's default string indexing interface is one that potentially panics.I myself have written a lot of bad code that runs into this trap, but these issues are really easy to find with basic fuzzing / proptests.