Overall, we’ve haven’t reached the kind of support for String.rev
that I was hoping for, so I think we can put this to rest. Probably didn’t help that there’s a separate heated Stdlib
conversation happening. If you find a good use for String.rev
feel free to revive this thread. I’ll summarize the discussion from above, but I will take the liberty to add some arguments for both sides.
Arguments against String.rev
The main objection to String.rev
is that it’s not generic enough, at least not to the same level as List.rev
where it is necessary because lists are often created in a reverse order or often represent ordered sequences where it is useful to be able to reverse that order.
I was going to argue that you can sometimes consider a string to be a “representation of an ordered sequence” of bytes and sometimes you need to reverse that order but I don’t think it would have convincing enough for @octachron, especially since we have String.fold_right
now. Plus @c-cube suggested Bytes.rev
being more appropriate.
A second objection to String.rev
is that it’s not meaningful if your bytes represent Unicode code-points. Unicode is honestly too messy, and I am not convinced that we shouldn’t have things that work with Latin1 strings just because they don’t work with Unicode strings.
A third objection to String.rev
is that we can implement it in one-line, so do we really need it?
Arguments in support of String.rev
It is in most of the alternative standard libraries. All the Stdlib
alternatives contain rev
, but neither of the String module alternatives I know of do (astring
and stringext
). So there is some conflicting evidence there.
It’s just useful sometimes! E.g. as a quick hacks to check for palindromes, for printing bytes in reverse order for debugging, etc.
Alternatives Suggested
Bytes.rev
- Slice notation.
Bytes.rev_in_place
might also be useful. Additionally, String.of_list
and String.to_list
would allow for an easy one-liner with List.rev
.
How to reverse a string on OCaml
If you found this thread looking for how to reverse a string, here are some examples.
let rev x =
String.to_seq x |> List.of_seq |> List.rev |> List.to_seq |> String.of_seq
let rev x =
let len = String.length x in
String.init len (fun n -> String.get x (len - n - 1))