Skip to content

Reverse String

Reverse a string by its characters as a reader sees them, so combining marks stay on their letters.

Adapted from Exercism’s problem specification (MIT). Listed under Strings & Text.

// FILE: reverse_string.nomi
//# Reverses a string.

/// Reverses `text` by grapheme, so a combining mark stays on its letter.
pub fn reverse(text: String) -> String
    String.reverse(text)
end

// FILE: reverse_string_test.nomi
import reverse_string.reverse

test "reverses strings"
    [
        ("an empty string",                         "",               ""),
        ("a word",                                  "robot",          "tobor"),
        ("a capitalized word",                      "Ramen",          "nemaR"),
        ("a sentence with punctuation",             "I'm hungry!",    "!yrgnuh m'I"),
        ("a palindrome",                            "racecar",        "racecar"),
        ("an even-sized word",                      "drawer",         "reward"),
        ("wide characters",                         "子猫",           "猫子"),
        ("grapheme cluster with pre-combined form", "Würstchenstand", "dnatsnehctsrüW"),
        ("grapheme clusters",                       "ผู้เขียนโปรแกรม",   "มรกแรปโนยขีเผู้"),
    ]
    |> subtests (description, text, expected), description
        assert reverse(text) == expected
    end
end
  • The solution is String.reverse, which already reverses by grapheme, so the two grapheme-cluster cases pass with no extra work. A hand-written Iter.reverse(text) |> String.join() does the same thing and would only restate the stdlib.