Stream: beginners

Topic: code golf


view this post on Zulip jan kili (Jan 23 2022 at 06:20):

Can anyone think of a shorter way to transform "ping" to "pong"?

» "ping" |> Str.toUtf8 |> List.mapWithIndex (\i, c -> if i == 1 then (List.get (Str.toUtf8 "o") 0 |> Result.withDefault 0) else c) |> Str.fromUtf8 |> Result.withDefault ""

"pong" : Str

» "ping" |> Str.toUtf8 |> List.set 1 (List.get (Str.toUtf8 "o") 0 |> Result.withDefault 0) |> Str.fromUtf8 |> Result.withDefault ""

"pong" : Str

»

view this post on Zulip jan kili (Jan 23 2022 at 06:21):

or a cleaner/faster/cooler way :)

view this post on Zulip jan kili (Jan 23 2022 at 07:14):

Whoops, I was so distracted by the original "arbitrary string" context (unexplained) that this question arose from... that I neglected the obvious-in-hindsight solution:

» "ping" |> Str.split "i" |> Str.joinWith "o"

"pong" : Str

»

view this post on Zulip Richard Feldman (Jan 23 2022 at 13:21):

we should also really have Str.replaceAll : Str, Str, Str -> Str (and also Str.replaceFirst and Str.replaceLast) so you can do "ping" |> Str.replaceAll "i" "o"


Last updated: Jul 26 2025 at 12:14 UTC