Skip to content

OCR Numbers

Read the digits a scanner drew with pipes and underscores, three columns and four rows per digit, and join several lines of them with commas.

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

// FILE: ocr_numbers.nomi
//# Reads digits drawn with pipes and underscores, three columns by four rows
//# each.

/// Why rows cannot be read.
pub enum Error
    LinesNotMultipleOfFour
    ColumnsNotMultipleOfThree
end

/// The ten digits as the scanner draws them, 0 to 9, three columns and four
/// rows each.
once font = [
    " _     _  _     _  _  _  _  _ ",
    "| |  | _| _||_||_ |_   ||_||_|",
    "|_|  ||_  _|  | _||_|  ||_| _|",
    "                              ",
]

/// Each digit's drawing, its four rows of three characters joined, to the
/// digit.
once digits = font |> glyphs() |> Iter.zip("0123456789") |> Iter.to_map()

/// The number `rows` draw: each four rows are a line of digits, each three
/// columns a digit, and the lines are joined by commas. A drawing that is
/// no digit reads as `?`.
pub fn convert(rows: List<String>) -> Result<String, Error>
    if Iter.count(rows) % 4 != 0 then return Err(.LinesNotMultipleOfFour)

    if Iter.any_match(rows, &(String.length(&1) % 3 != 0)) then
        return Err(.ColumnsNotMultipleOfThree)
    end

    rows
    |> Iter.chunks(4)
    |> Iter.map(read_line)
    |> String.join(",")
    |> Ok()
end

/// The digits one line of four rows draws.
fn read_line(line: List<String>) -> String
    line
    |> glyphs()
    |> Iter.map(&(Map.get(digits, &1) |> Maybe.with_default("?")))
    |> String.join()
end

/// Each digit's drawing in four `rows`, left to right: the rows cut into
/// three-column cells, read down each column of cells.
fn glyphs(rows: List<String>) -> List<String>
    rows
    |> Iter.map(fn row -> row |> Iter.chunks(3) |> Iter.map(String.join))
    |> Iter.transpose()
    |> Iter.map(String.join)
    |> Iter.to_list()
end

// FILE: ocr_numbers_test.nomi
import ocr_numbers.{self, Error}

test "convert"
    [
        (
            "Recognizes 0",
            [
                " _ ",
                "| |",
                "|_|",
                "   ",
            ],
            Ok("0"),
        ),
        (
            "Recognizes 1",
            [
                "   ",
                "  |",
                "  |",
                "   ",
            ],
            Ok("1"),
        ),
        (
            "Unreadable but correctly sized inputs return ?",
            [
                "   ",
                "  _",
                "  |",
                "   ",
            ],
            Ok("?"),
        ),
        (
            "Input with a number of lines that is not a multiple of four raises an error",
            [
                " _ ",
                "| |",
                "   ",
            ],
            Err(Error.LinesNotMultipleOfFour),
        ),
        (
            "Input with a number of columns that is not a multiple of three raises an error",
            [
                "    ",
                "   |",
                "   |",
                "    ",
            ],
            Err(.ColumnsNotMultipleOfThree),
        ),
        (
            "Recognizes 110101100",
            [
                "       _     _        _  _ ",
                "  |  || |  || |  |  || || |",
                "  |  ||_|  ||_|  |  ||_||_|",
                "                           ",
            ],
            Ok("110101100"),
        ),
        (
            "Garbled numbers in a string are replaced with ?",
            [
                "       _     _           _ ",
                "  |  || |  || |     || || |",
                "  |  | _|  ||_|  |  ||_||_|",
                "                           ",
            ],
            Ok("11?10?1?0"),
        ),
        (
            "Recognizes 2",
            [
                " _ ",
                " _|",
                "|_ ",
                "   ",
            ],
            Ok("2"),
        ),
        (
            "Recognizes 3",
            [
                " _ ",
                " _|",
                " _|",
                "   ",
            ],
            Ok("3"),
        ),
        (
            "Recognizes 4",
            [
                "   ",
                "|_|",
                "  |",
                "   ",
            ],
            Ok("4"),
        ),
        (
            "Recognizes 5",
            [
                " _ ",
                "|_ ",
                " _|",
                "   ",
            ],
            Ok("5"),
        ),
        (
            "Recognizes 6",
            [
                " _ ",
                "|_ ",
                "|_|",
                "   ",
            ],
            Ok("6"),
        ),
        (
            "Recognizes 7",
            [
                " _ ",
                "  |",
                "  |",
                "   ",
            ],
            Ok("7"),
        ),
        (
            "Recognizes 8",
            [
                " _ ",
                "|_|",
                "|_|",
                "   ",
            ],
            Ok("8"),
        ),
        (
            "Recognizes 9",
            [
                " _ ",
                "|_|",
                " _|",
                "   ",
            ],
            Ok("9"),
        ),
        (
            "Recognizes string of decimal numbers",
            [
                "    _  _     _  _  _  _  _  _ ",
                "  | _| _||_||_ |_   ||_||_|| |",
                "  ||_  _|  | _||_|  ||_| _||_|",
                "                              ",
            ],
            Ok("1234567890"),
        ),
        (
            "Numbers separated by empty lines are recognized. Lines are joined by commas.",
            [
                "    _  _ ",
                "  | _| _|",
                "  ||_  _|",
                "         ",
                "    _  _ ",
                "|_||_ |_ ",
                "  | _||_|",
                "         ",
                " _  _  _ ",
                "  ||_||_|",
                "  ||_| _|",
                "         ",
            ],
            Ok("123,456,789"),
        ),
    ]
    |> subtests (description, rows, expected), description
        assert ocr_numbers.convert(rows) == expected
    end
end
  • convert returns Result<String, Error>. The two canonical errors, a row count that is not a multiple of four and a row width that is not a multiple of three, are the Error variants LinesNotMultipleOfFour and ColumnsNotMultipleOfThree. A drawing that is no digit is not an error: it reads as ?, as the canonical data asks.
  • The digits are not a hand-written table of twelve-character keys. font is the ten digits drawn the way the input draws them, and digits reads the font with the same glyphs function the input goes through, zipped with "0123456789" into a map. The font and the reader cannot disagree.
  • glyphs cuts each row into three-column cells (Iter.chunks(3) over the row’s graphemes, each cell joined back into a String), then Iter.transpose turns four rows of cells into the cells of each digit, top to bottom, and each digit’s cells are joined into one key.
  • The lines are Iter.chunks(4) over the rows, each read with read_line and joined with commas. A cell drawing missing from digits is the ? the canonical data expects, so Maybe.with_default("?") is the rule, not a guess.
  • String.join is passed as a function, Iter.map(String.join); its separator defaults to "".
  • The 17 canonical cases are one subtests table. Each row’s drawing is a list written one string per line, so the rows read as the picture they are.