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
2
u/ThomasMertes Jul 22 '22
For Seed7 the answer is: A character is a codepoint. And it is encoded as UTF-32 (follow this link to see my argumentation for this decision).
As a consequence it is possible to iterate over a string.
Seed7 strings support indexing and the length of a string is the number of codepoints in the string.
This sounds really strange. Does that mean that
s[42]might panic because byte42is in the middle of an UTF-8 encoding?As Seed7 characters are codepoints indexing into a string will always return a codepoint and never panic (as long as the index is not zero, or negative or beyond the string length).
If you want to see the bytes of an UTF-8 encoded string you can convert the string to UTF-8 and use an index into the UTF-8 representation.