Skip to content

Acronym

Build an acronym from the first letter of each word of a phrase, treating hyphens as word separators and ignoring other punctuation.

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

// FILE: acronym.nomi
//# The acronym of a phrase, from the first letter of each word.

import std::regex.Regex

/// The acronym of `phrase`: the first letter of each word, upper-cased.
/// Hyphens and other punctuation separate words; an apostrophe does not.
pub fn abbreviate(phrase: String) -> String
    phrase
    |> String.find_all(Regex"[A-Za-z][A-Za-z']*")
    |> Iter.map(&String.take(&1, 1))
    |> String.join()
    |> String.uppercase()
end

// FILE: acronym_test.nomi
import acronym.abbreviate

test "abbreviates phrases"
    [
        ("basic",                          "Portable Network Graphics",               "PNG"),
        ("lowercase words",                "Ruby on Rails",                           "ROR"),
        ("punctuation",                    "First In, First Out",                     "FIFO"),
        ("all caps word",                  "GNU Image Manipulation Program",          "GIMP"),
        ("punctuation without whitespace", "Complementary metal-oxide semiconductor", "CMOS"),
        (
            "very long abbreviation",
            "Rolling On The Floor Laughing So Hard That My Dogs Came Over And Licked Me",
            "ROTFLSHTMDCOALM",
        ),
        ("consecutive delimiters", "Something - I made up from thin air", "SIMUFTA"),
        ("apostrophes",            "Halley's Comet",                      "HC"),
        ("underscore emphasis",    "The Road _Not_ Taken",                "TRNT"),
    ]
    |> subtests (description, phrase, expected), description
        assert abbreviate(phrase) == expected
    end
end
  • Words are found with one regex, [A-Za-z][A-Za-z']*, through String.find_all, rather than splitting on spaces and hyphens and then stripping punctuation. The regex makes “Halley’s” one word and “Not” the word “Not” without special cases.
  • The first letter of a word is &String.take(&1, 1), a capture rather than fn word -> .... Iter.first(word) also works but returns a Maybe, and every match has at least one letter.
  • The whole acronym is upper-cased once at the end, not letter by letter.