Is there no function to get a character in a string yet? Would I need to list the graphemes and index into that list, e.g. write my own function for now?
Yes, so: Str.graphemes "hello" |> List.get 3
Is it common in stdlibs of other programming languages to do this in one function?
very
Confirmed: python, js, scala and java have it.
I'm in favor of adding it
yea.. tho their str representation is very different
so i think a str index function would be a linear algorithm
meaning for each index you ask, you have to traverse all over again
so it might just be preferable to convert to grapheme list once
good point!
Seems like it would still be nice to have a graphemeAt
function but also a clippy-like performance warning if it is used repeatedly on the same string.
yeah this is a tricky topic, and unfortunately most languages present a footgun (probably for historical reasons, at least originally)
the tradeoffs are:
offering "get a “character” in constant time" (with the note that what "character" means varies by language) seems to me the most likely reason that emojis commonly break software
so Swift doesn't offer that functionality, and I don't think Roc should either - for the same reasons!
so although Str.graphemes "hello" |> List.get 3
is obviously slow, I think that's a feature and not a bug :big_smile:
because Str.graphemesAt
would also be slow, but not obviously so
and yes, if you needed to do multiple "get grapheme by index" it would indeed often be faster to make the list of graphemes once, and then index into that list multiple times (each access being constant time) than to do multiple linear scans of the string
so I'd propose that maybe explaining all of this in the Str
docs is maybe the best solution here!
Yes, good reasoning!
Last updated: Jul 06 2025 at 12:14 UTC