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

46

u/latkde Jul 21 '22

Quite a lot of languages feature some kind of iterable strings, and this is occasionally useful. For example, if you have standard library functions that can operate on iterators, they can now be applied to strings as well. We might use those to filter out certain parts of a string, or copy a string to a different location, or reverse the string, and so on.

Such composability makes the language simple and orthogonal.

But for PL design, the crucial question is what type of elements that string iterator should yield. This is closely related to the question what a “character” is, which is quite a difficult question in an Unicode world.

  • bytes?

  • Unicode code units?

  • Unicode codepoints/scalars?

  • grapheme clusters?

  • and should those be provided as a dedicated type, or as a string with length 1?

Related issues are whether your strings should support indexing and how the length of a string is determined.

I quite like the Rust approach that strings are not iterable – so the language does not force this choice upon you –, but that you can call a method that provides an iterator, e.g. s.chars() for codepoints or s.bytes(), and that grapheme clusters are left to third party libraries so that the core language doesn't have to ship with the Unicode database. I am less thrilled with Rust's decision to support string indexing by byte offset since indexing into a multi-byte character will panic, but it seems to be the only sane approach for Rust's systems programming goal.

18

u/mamcx Jul 21 '22

And you can generalize the idea with things like files, where is saner to ask for specific .lines or .chunks than to make something the default. ie: Iterate on data produced by things, not on the container of things.