Created
August 3, 2019 19:10
-
-
Save reckenrode/83118c53d72278767b45e7995ba575c6 to your computer and use it in GitHub Desktop.
Unicode-aware string reverse in F#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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