Skip to content

Instantly share code, notes, and snippets.

@reckenrode
Created August 3, 2019 19:10
Show Gist options
  • Save reckenrode/83118c53d72278767b45e7995ba575c6 to your computer and use it in GitHub Desktop.
Save reckenrode/83118c53d72278767b45e7995ba575c6 to your computer and use it in GitHub Desktop.
Unicode-aware string reverse in F#
open System.Text
open System
open ICU4N.Text
let reverse (str: string) =
if str.Length <= 0 then
str
else
let span = str.AsSpan ()
let breaks = seq {
let iterator = BreakIterator.GetCharacterInstance ()
iterator.SetText str
let mutable previous = 0
while iterator.Next () <> BreakIterator.Done do
yield (previous, iterator.Current - previous)
previous <- iterator.Current
}
let breaks = breaks |> Seq.fold (fun xs x -> x :: xs) []
let builder = StringBuilder ()
for (idx, len) in breaks do
let span = span.Slice (idx, len)
builder.Append span |> ignore
builder.ToString ()
[<EntryPoint>]
let main args =
match args |> Array.tryHead with
| Some str -> printfn "“%s” (len: %d) reverses to “%s”" str (str |> String.length) (reverse str)
| _ -> printfn "Usage: reverse <string to reverse>"
0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment