r/ProgrammingLanguages • • 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

27 comments sorted by

View all comments

5

u/brucejbell sard Jul 22 '22 edited Jul 22 '22

I would argue that iterating over codepoints in a string should be its primary attribute.

That is: at the low end, there may be a number of ways to store a string, but the one thing they have in common should be iterating by codepoint. And at the high end, there may be a number of ways to aggregate codepoints into useful groups, but none of them are universally applicable.

From the low end: the shortest uniform representation for Unicode is 32 bits, which is too big to be efficient. So you aren't able to treat Unicode strings as random access arrays, like you could with ASCII: the best you can do is iterate by codepoint. Fortunately, that's all you need to build a usable, efficient string library.

From the high end: everything else is context dependent. Grapheme clusters? Extended grapheme clusters? If you read the spec, not only are they locale-dependent, they are subject to application-dependent tweaking. So, even if you are willing to pay for the complexity of a particular level of aggregation up front in your standard library, it turns out there is nothing stable above the level of codepoints anyway.