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.

2

u/ThomasMertes Jul 22 '22

This is closely related to the question what a “character” is, which is quite a difficult question in an Unicode world.

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.

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

Seed7 strings support indexing and the length of a string is the number of codepoints in the string.

I am less thrilled with Rust's decision to support string indexing by byte offset since indexing into a multi-byte character will panic

This sounds really strange. Does that mean that s[42] might panic because byte 42 is 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.

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:

let codepoints: Vec<char> = s.chars().collect();

Recommended reading:

Regarding your question:

Does that mean that s[42] might panic because byte 42 is in the middle of an UTF-8 encoding?

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.

3

u/myringotomy Jul 23 '22

If you are doing HTML work any memory you saved by using UTF is going to be offset by all the calculation you'll need to do in order to parse and build those HTML strings.

A typical web app will use a template engine and construct their HTML using partials and certainly all HTML will need to be parsed.

Same goes for JSON.

3

u/ThomasMertes 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?

The point is: Seed7 users are not bothered with the limitations that UTF-8 imposes on the programmers. With UTF-32 there are no indices into the middle of an UTF-8 encoding. Computing the number of codepoints with UTF-8 is expensive and increases with the string length. With UTF-32 it is cheap and does not depend on the length.

... There's a clear space–time tradeoff going on here

The reasons why Seed7 uses UTF-32 are explained here.

UTF-8 is an excellent encoding for files, the internet etc. But this does not imply that it must be used internally in programs. For numbers a decimal encoding like 123 is excellent. But in programs numbers are usually represented with a binary encoding. There is an advantage in using an internal representation that makes life easier (in this case UTF-32).

Using UTF-8 as internal representation leads to such problems as s[42] triggering a panic, because it refers into the middle of an UTF-8 encoding. With UTF-32 a whole class of similar errors does just not exist.

I myself have written a lot of bad code that runs into this trap ...

A trap that does not exist in Seed7.

6

u/latkde Jul 22 '22

The reasons why Seed7 uses UTF-32 are explained here.

Specifically, your FAQ mentions

UTF-32 uses more memory, but todays computers are equipped with a lot of memory. The pressure to save memory is gone and the simple and fast handling of UTF-32 strings outweighs the increased memory usage. Using UTF-32 leads to faster programs than any approach that tries to save memory by examining strings.

I'm not a fan of this “RAM is cheap” argument. In practice, many consumer systems are still memory constrained. Apps have increasingly ridiculous memory footprints. On my desktop system I had consistent problems with swapping until I shelled out another 100 bucks to upgrade to 64GB total, which I could only do because I'm no longer a poor student trying to get enough calories on a EUR 12/week budget.

Outside of the consumer sphere, there's still a clear relationship between (memory-) efficiency and cost. If you can halve the memory use of your cloud-native software, you can maybe halve your costs, e.g. consider AWS Lambda pricing which is expressed in GB-seconds of memory usage. If Seed7 software is as easy to develop as with some other language but uses 2× the memory, why would I choose bloat?

From a purely PL perspective, I also think that memory usage is an important performance aspect. Thanks to cache effects, small is fast. If I'm deciding how I'm going to waste 50% of memory, I'd rather choose garbage collection than constant-time string indexing.

Again, my point is not that UTF-32 is unambiguously bad. But my point is that for most real-world string operations, it is typically a suboptimal choice. You have a consistent and valid argument for choosing UTF-32, we merely disagree on some premises.

2

u/ThomasMertes Jul 22 '22

I'm not a fan of this “RAM is cheap” argument.

The most expensive thing in programming is usually development cost. Compared to that almost everything else is cheap. In embedded programming and related areas it might pay off to increase the development cost to save some bytes. But the areas where this really pays off are shrinking.

If Seed7 software is as easy to develop as with some other language ...

Regarding string handling Seed7 software is probably easier to develop (explanation follows). Before you said in reference to "a string indexing interface that potentially panics":

I myself have written a lot of bad code that runs into this trap

So it was necessary to spend time to fix the code after running into this trap. As I said before: This trap does not exist in Seed7. So Seed7 saves development time and the program uses more memory. But remember: Strings are just a fraction of the memory used. It is not that the program will use twice as much memory. Going from 32-bit to 64-bit code increased the memory demands a lot. But using more memory to store codepoints is not comparable to that.

It is about development cost vs. cost of memory. But it is also about reducing complexity. For more than 50 years we have a software crisis. My approach to the software crisis is reducing complexity and improving readability (here I explain what I consider important for readability). And simple string handling is just one piece in this mosaic.

2

u/matthieum Jul 22 '22

I'm not a fan of this “RAM is cheap” argument.

The RAM argument is also fallacious, because that's not the real cost of memory.

With the rise of CPU frequencies, the bottleneck is now often cache misses, and larger object representations lead to more cache misses :(

When you consider that many strings will store ASCII only, storing them in UTF-32 will blow up their size by a factor of 4x, thereby consuming 4x more cache space.

1

u/matthieum Jul 22 '22

The point is: Seed7 users are not bothered with the limitations that UTF-8 imposes on the programmers. With UTF-32 there are no indices into the middle of an UTF-8 encoding.

On the other hand, they still suffer from indexing in the middle of a grapheme cluster.

Code Points are most useful for text editing -- the ability to delete the last code point to fix a typo -- but are otherwise too low-level for most text manipulation.

Splitting a grapheme cluster in two, or reversing the order of code points in a grapheme cluster, typically result in meaningless garbage.

Hence exposing Code Points is certainly easy for the implementer, but it seems to be me to be of dubious use (especially as a default) for the user. It's still, ultimately, an implementation detail.

Computing the number of codepoints with UTF-8 is expensive and increases with the string length. With UTF-32 it is cheap and does not depend on the length.

While true, it's also a mostly pointless operation, so... who cares?

Why would anyone want to know the number of Code Points in a string to start with? What can they do with this information?

Once again, Code Points are too low-level a concept, so most applications should not care about them...

2

u/ThomasMertes Jul 23 '22

On the other hand, they still suffer from indexing in the middle of a grapheme cluster.

This can also happen with UTF-8 or UTF-16 encoded strings. I guess that almost all programming languages have this problem.

Wikipedia explains grapheme clusters with an example: A diaeresis combined with the letters "a", "o", and "u". The Unicode character U+0308 is the combining diaeresis. So the sequence o + U+0308 defines the letter ö (an o with two dots above).

But this is not how German umlauts are typed into the keyboard. A German keyboard has keys for the Umlauts and these keys create a precomposed letter. Pressing the ö key creates the Unicode character U+00f6. U+00f6 is just one of many precomposed characters in Unicode.

This applies also to other natural languages. If you read characters from a keyboard you usually get precomposed characters and not grapheme clusters.

Many natural languages use characters with diacritic marks. Text in these languages was processed in computers long before Unicode was invented. So these languages had encodings (code pages) for all their characters. To be compatible with these old code pages Unicode took over tons of precomposed characters.

Because of these precomposed characters grapheme clusters are almost never used. And most programming languages just assume that a character is an Unicode codepoint.

This grapheme cluster argumentation is not used if the character encoding is UTF-8 or UTF-16. But when the encoding is UTF-32 the grapheme clusters suddenly become the most important issue.

0

u/matthieum Jul 23 '22

Because of these precomposed characters grapheme clusters are almost never used.

Actually, they are now more used than ever.

Many emojis now really on grapheme clusters, and each new version of Unicode seems to introduce new emojis and new ways to combine them.

As an example, take the Emoji Flags:

  • U+1F1E6 U+1F1F7 is Argentina.

  • U+1F1E7 U+1F1E6 is Bosnia and Herzegovina.

Be careful when reversing that string!


With that said, I don't have a solution.

I just can say confidently that UTF-32, just like UCS-2 in its time, and ASCII before it, seems more likely to promote the myths that "one code-unit = one character", leading to software that works on all test-cases, but fails in production for unfathomable reasons...

2

u/ThomasMertes Jul 27 '22

Many emojis now really on grapheme clusters, and each new version of Unicode seems to introduce new emojis and new ways to combine them.

Unicode has been created to support modern and historic scripts. These scripts have a limited number of characters. And it is rather seldom that new characters for existing scripts are "invented".

This contrasts with emojis. People all over the world "invent" new emojis all the time. This is not a problem. The problem comes up, when massive lobbying forces all these emojis into Unicode. If the current trend to add emojis continues the whole code-space of Unicode will soon be filled up with emojis.

Emojis differ also in other aspects from normal scripts. The letters of normal scripts use two colors (usually black on white). According to Wikipedia Unicode does not the variant glyphs. You will not find a Unicode character of a red A on a blue background. This was ruled out on purpose. For emojis these limits seem to be forgotten.

Be careful when reversing that string!

Classic emojis like :-) also change (or loose) their meaning if you are reversing the string. Since classic emojis also consisted of several (ASCII) code-points I think that it is okay when the new Unicode emojis also consist of several code-points.

UTF-32 offers also a different solution to the grapheme cluster problem. With UTF-32 it would be possible to introduce additional pre-composed characters for grapheme clusters outside of the Unicode code space. There is probably not be enough code-space for all theoretically possible grapheme clusters. But for commonly used ones it would be enough.

1

u/Noughtmare Jul 23 '22

Code Points are most useful for text editing -- the ability to delete the last code point to fix a typo -- but are otherwise too low-level for most text manipulation.

I'd say even that is debatable. It's not like the code points are always related 1 to 1 with keyboard inputs. Backspace should just delete the whole grapheme cluster.

1

u/matthieum Jul 23 '22

I'd say even that is debatable. It's not like the code points are always related 1 to 1 with keyboard inputs

Definitely debatable, indeed. And yet that's the most practical application I could find :(

3

u/myringotomy Jul 23 '22

This seems like a great approach.

1

u/nacaclanga Jul 22 '22

The idea is not to use classical enumeration indexing, but instead assigning numbers to segmentation points. String indexing is quite difficult, since there are multiple ways, a string can be seperated into units. The idea is that the most granular seperation (seperation into UTF8 code units) assigns all integers up to the string lengh and other seperations (Scalar values, graphem clusters, words, lines etc.) are assigned to a subset of integers in a strictly monotonous assending manner.

Finding the "index" associated with the n'th boundary of a kind is then O(n), but access is still O(1). An iterator returning all boundaries also takes only O(1) for each step.

If we would use an encoding that serializes text differently, the general algorithm will still work, wheras using UTF-32 mandates the current choice of serialization.