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
endok reverses strings (9 cases)
test result: ok. 9 passed, 0 failed
How it’s written
Section titled “How it’s written”- The solution is
String.reverse, which already reverses by grapheme, so the two grapheme-cluster cases pass with no extra work. A hand-writtenIter.reverse(text) |> String.join()does the same thing and would only restate the stdlib.