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
»
or a cleaner/faster/cooler way :)
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
»
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