Skip to content

Matrix

Read a matrix of numbers from text, one row per line, and answer any row or column.

Adapted from Exercism’s problem specification (MIT). Listed under Grids & Matrices.

// FILE: matrix.nomi
//# A matrix read from text, and its rows and columns.

/// A matrix of numbers read from text, one row per line.
pub opaque struct Matrix
    rows: Vector<Vector<Int>>
end

/// Why text is not a matrix.
pub enum Error
    NotANumber String
end

impl Matrix
    /// The matrix whose rows are the lines of `text`, each a list of numbers
    /// separated by spaces, or `NotANumber` with the first word that is not
    /// one.
    pub fn parse(text: String) -> Result<Matrix, Error>
        rows =
            text
            |> String.lines()
            |> Iter.map(parse_row)
            |> Result.collect()?
            |> Iter.to_vector()

        Ok({rows:})
    end

    /// The numbers of row `index`, counted from 1, or `None` past the last.
    pub fn row(matrix: Matrix, index: Int) -> Maybe<List<Int>>
        matrix.rows
        |> Vector.get(index - 1)?
        |> Iter.to_list()
        |> Some()
    end

    /// The numbers of column `index`, counted from 1, top to bottom, or
    /// `None` past the last.
    pub fn column(matrix: Matrix, index: Int) -> Maybe<List<Int>>
        matrix.rows
        |> Iter.map(&Vector.get(&1, index - 1))
        |> Maybe.collect()
    end
end

fn parse_row(line: String) -> Result<Vector<Int>, Error>
    line
    |> String.words()
    |> Iter.map(fn word -> String.to_int(word) |> Maybe.to_result(Error.NotANumber(word)))
    |> Result.collect()?
    |> Iter.to_vector()
    |> Ok()
end

// FILE: matrix_test.nomi
import matrix.Matrix

test "rows"
    [
        ("extract row from one number matrix",              "1",          1, [1]),
        ("can extract row",                                 "1 2\n3 4",   2, [3, 4]),
        ("extract row where numbers have different widths", "1 2\n10 20", 2, [10, 20]),
        (
            "can extract row from non-square matrix with no corresponding column",
            "1 2 3\n4 5 6\n7 8 9\n8 7 6",
            4,
            [8, 7, 6],
        ),
    ]
    |> subtests (description, text, index, expected), description
        assert Ok(matrix) = Matrix.parse(text)

        assert Matrix.row(matrix, index) == Some(expected)
    end
end

test "columns"
    [
        ("extract column from one number matrix", "1",                   1, [1]),
        ("can extract column",                    "1 2 3\n4 5 6\n7 8 9", 3, [3, 6, 9]),
        (
            "can extract column from non-square matrix with no corresponding row",
            "1 2 3 4\n5 6 7 8\n9 8 7 6",
            4,
            [4, 8, 6],
        ),
        (
            "extract column where numbers have different widths",
            "89 1903 3\n18 3 1\n9 4 800",
            2,
            [1903, 3, 4],
        ),
    ]
    |> subtests (description, text, index, expected), description
        assert Ok(matrix) = Matrix.parse(text)

        assert Matrix.column(matrix, index) == Some(expected)
    end
end

// Not canonical: the canonical matrices are all well formed and every index
// is in range.
test "a word that is not a number is an error"
    assert Matrix.parse("1 2\n3 four") == Err(.NotANumber("four"))
end

test "an index past the last row or column is None"
    matrix = Matrix.parse("1 2\n3 4")?

    assert Matrix.row(matrix, 3) == None
    assert Matrix.column(matrix, 0) == None
end
  • Matrix.parse reads the text once into an opaque struct of a Vector<Vector<Int>>, so row and column index it and never parse again. Each line is split with String.words, which ignores the different widths of the numbers.
  • A word that is not a number is Err(Error.NotANumber(word)), through Maybe.to_result per word and Result.collect()? per row and over the rows. row is Vector.get(index - 1)? as one stage of a pipe. The canonical data has no such case; the test file adds one, marked not canonical.
  • row and column count from 1, as the canonical data does, and answer Maybe<List<Int>>: an index past the last row or column is None, which the test file also checks outside the canonical cases. column is Vector.get on every row, gathered with Maybe.collect, so it is None if any row is too short.
  • The row and column groups are one subtests table each, named by the description column. A row’s body takes the matrix apart with assert Ok(matrix) = Matrix.parse(text), since a ? cannot leave a subtests row.