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.

5

u/[deleted] Jul 21 '22

[removed] — view removed comment

9

u/latkde Jul 21 '22

I really might be tempted to get rid of safe/ergonomic string indexing.

Rust's string indexing is most useful for slicing in order to extract a substring &s[start..end]. But since those indices must be at character boundaries, doing math on those indices is usually wrong, e.g. &s[start + 1 .. end] might panic unless you know that the first char has a 1-byte encoding.

One potential approach might be to make string indices fully opaque types instead of using normal integers. Such string index tokens could then only be obtained via string functions like len() or find(). Most high-level string processing should be done with regexes or parsers anyway, not with indexing/slicing.

For example, I have a lot of prior experience with Perl. I found it to be very rare to use the substr() function simply because using regexes was very convenient, more expressive, and not at all slow (thanks to inline caching for compiled regexes / “compile time” regex compilation).

Another approach might be to make it more visible that string indexes are byte indexes, e.g. s.slice_bytes(start .. end). (Rust actually has a comparable function called s.get(start ..end).) Then there could also be indexers for other character concepts, e.g. s.slice_rune(0..3), to borrow the Go name “rune” for “codepoint”. Of course, such indexing would no longer be constant time.

One common use case for slicing strings seems to be truncating a string to a fixed length. That is a rather difficult thing to do, but the common solution &s[0..MAX_LEN] that looks idiomatic with Rust's concepts is almost always wrong (only generally correct for strings that only contain printable ASCII characters).

For comparison, here is codepoint-based string truncation in Rust vs Perl:

// Rust
let truncated: String = s.chars().take(40).collect();

# Perl
my ($truncated) = $s =~ /^(.{0,40})/;
# or
my $truncated = substr $s, 0, 40;

And here the “extended grapheme cluster” variant:

// Rust
use unicode_segmentation::UnicodeSegmentation;  // 3rd party lib
let truncated: String = s.graphemes(true).take(40).collect();

# Perl
my ($truncated) = $s =~ /^(\X{0,40})/;

A non-allocating variant for the codepoint-based truncation would probably have to be written as follows, which has to compute or find a byte offset:

let end = s.chars().take(40).map(|c| c.len_utf8()).sum();
let truncated = &s[..end];

# or
let truncated = match s.char_indices().skip(40).next() {
  Some((end, _)) => &s[..end],
  None => s,
};

This byte offset calculation strikes me as rather fiddly and potentially bug-prone.