Skip to content

Phone Number

Clean a NANP phone number down to its ten digits, or say why it is not one.

Adapted from Exercism’s problem specification (MIT). Listed under Parsing & Validation.

// FILE: phone_number.nomi
//# Cleans up a North American phone number written by a user.

/// Why a phrase is not a NANP phone number.
pub enum Error
    Letters
    Punctuation
    TooFewDigits
    TooManyDigits
    CountryCodeNotOne
    AreaCodeStartsWithZero
    AreaCodeStartsWithOne
    ExchangeCodeStartsWithZero
    ExchangeCodeStartsWithOne
end

/// Cleans a NANP phone number down to its ten digits, dropping punctuation
/// and a leading country code of 1.
pub fn clean(phrase: String) -> Result<String, Error>
    codepoints = String.to_codepoints(phrase)

    if Iter.any_match(codepoints, Codepoint.is_letter) then return Err(.Letters)

    if not Iter.all_match(codepoints, fn cp -> Codepoint.is_digit(cp) or is_separator(cp)) then
        return Err(.Punctuation)
    end

    digits =
        codepoints
        |> Iter.map(Codepoint.to_digit)
        |> Maybe.values()
        |> Iter.to_list()
        |> national()?

    case digits
        [0, ..]          -> Err(.AreaCodeStartsWithZero)
        [1, ..]          -> Err(.AreaCodeStartsWithOne)
        [_, _, _, 0, ..] -> Err(.ExchangeCodeStartsWithZero)
        [_, _, _, 1, ..] -> Err(.ExchangeCodeStartsWithOne)
        _                -> digits |> Iter.map(Int.to_string) |> String.join() |> Ok()
    end
end

/// Strips the country code from eleven digits, so ten remain.
fn national(digits: List<Int>) -> Result<List<Int>, Error>
    count = Iter.count(digits)

    case digits
        _ when count < 10            -> Err(.TooFewDigits)
        _ when count == 10           -> Ok(digits)
        [1, ..rest] when count == 11 -> Ok(rest)
        _ when count == 11           -> Err(.CountryCodeNotOne)
        _                            -> Err(.TooManyDigits)
    end
end

fn is_separator(cp: Codepoint) -> Bool
    cp is (' ' or '(' or ')' or '-' or '.' or '+')
end

// FILE: phone_number_test.nomi
import
    phone_number
    phone_number.Error
end

test "cleans phone numbers"
    [
        ("cleans the number", "(223) 456-7890", Ok("2234567890")),
        ("cleans numbers with dots", "223.456.7890", Ok("2234567890")),
        ("cleans numbers with multiple spaces", "223 456   7890   ", Ok("2234567890")),
        ("invalid when 9 digits", "123456789", Err(Error.TooFewDigits)),
        ("invalid when 11 digits does not start with a 1", "22234567890", Err(.CountryCodeNotOne)),
        ("valid when 11 digits and starting with 1", "12234567890", Ok("2234567890")),
        (
            "valid when 11 digits and starting with 1 even with punctuation",
            "+1 (223) 456-7890",
            Ok("2234567890"),
        ),
        ("invalid when more than 11 digits",   "321234567890",   Err(.TooManyDigits)),
        ("invalid with letters",               "523-abc-7890",   Err(.Letters)),
        ("invalid with punctuations",          "523-@:!-7890",   Err(.Punctuation)),
        ("invalid if area code starts with 0", "(023) 456-7890", Err(.AreaCodeStartsWithZero)),
        ("invalid if area code starts with 1", "(123) 456-7890", Err(.AreaCodeStartsWithOne)),
        (
            "invalid if exchange code starts with 0",
            "(223) 056-7890",
            Err(.ExchangeCodeStartsWithZero),
        ),
        (
            "invalid if exchange code starts with 1",
            "(223) 156-7890",
            Err(.ExchangeCodeStartsWithOne),
        ),
        (
            "invalid if area code starts with 0 on valid 11-digit number",
            "1 (023) 456-7890",
            Err(.AreaCodeStartsWithZero),
        ),
        (
            "invalid if area code starts with 1 on valid 11-digit number",
            "1 (123) 456-7890",
            Err(.AreaCodeStartsWithOne),
        ),
        (
            "invalid if exchange code starts with 0 on valid 11-digit number",
            "1 (223) 056-7890",
            Err(.ExchangeCodeStartsWithZero),
        ),
        (
            "invalid if exchange code starts with 1 on valid 11-digit number",
            "1 (223) 156-7890",
            Err(.ExchangeCodeStartsWithOne),
        ),
    ]
    |> subtests (description, phrase, expected), description
        assert phone_number.clean(phrase) == expected
    end
end
  • Errors are an Error enum, one variant per canonical error message; tests compare against variants, not message text.
  • The checks run in the order the canonical errors imply: letters, then punctuation, then digit count, then the area and exchange codes.
  • Digits become a List<Int>, so the area and exchange rules are list patterns ([_, _, _, 0, ..]) rather than string slicing.
  • national uses a case with when guards on the count, so the eleven-digit [1, ..rest] pattern can sit among them.
  • The work is per codepoint: Codepoint.is_letter finds letters, Codepoint.is_digit and is_separator find punctuation, and Codepoint.to_digit with Maybe.values keeps the digits as Ints in one stage. is_letter is Unicode, so é is a letter here, not punctuation; is_digit is ASCII only, so a full-width 1 is punctuation.
  • is_separator is one or pattern of the six separators and a _ arm.