Stream: beginners

Topic: get character in string?


view this post on Zulip itmuckel (Mar 31 2023 at 08:40):

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?

view this post on Zulip Anton (Mar 31 2023 at 09:03):

Yes, so: Str.graphemes "hello" |> List.get 3
Is it common in stdlibs of other programming languages to do this in one function?

view this post on Zulip dank (Mar 31 2023 at 09:19):

very

view this post on Zulip Anton (Mar 31 2023 at 09:26):

Confirmed: python, js, scala and java have it.
I'm in favor of adding it

view this post on Zulip dank (Mar 31 2023 at 09:34):

yea.. tho their str representation is very different

view this post on Zulip dank (Mar 31 2023 at 09:35):

so i think a str index function would be a linear algorithm

view this post on Zulip dank (Mar 31 2023 at 09:36):

meaning for each index you ask, you have to traverse all over again

view this post on Zulip dank (Mar 31 2023 at 09:36):

so it might just be preferable to convert to grapheme list once

view this post on Zulip Anton (Mar 31 2023 at 09:48):

good point!

view this post on Zulip Anton (Mar 31 2023 at 09:52):

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.

view this post on Zulip Richard Feldman (Mar 31 2023 at 11:29):

yeah this is a tricky topic, and unfortunately most languages present a footgun (probably for historical reasons, at least originally)

the tradeoffs are:

view this post on Zulip Richard Feldman (Mar 31 2023 at 11:30):

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

view this post on Zulip Richard Feldman (Mar 31 2023 at 11:30):

so Swift doesn't offer that functionality, and I don't think Roc should either - for the same reasons!

view this post on Zulip Richard Feldman (Mar 31 2023 at 11:31):

so although Str.graphemes "hello" |> List.get 3 is obviously slow, I think that's a feature and not a bug :big_smile:

view this post on Zulip Richard Feldman (Mar 31 2023 at 11:31):

because Str.graphemesAt would also be slow, but not obviously so

view this post on Zulip Richard Feldman (Mar 31 2023 at 11:32):

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

view this post on Zulip Richard Feldman (Mar 31 2023 at 11:32):

so I'd propose that maybe explaining all of this in the Str docs is maybe the best solution here!

view this post on Zulip itmuckel (Mar 31 2023 at 11:55):

Yes, good reasoning!


Last updated: Jul 06 2025 at 12:14 UTC