Skip to content

Wordy

Parse and evaluate simple arithmetic word problems, left to right.

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

// FILE: wordy.nomi
//# Parses and evaluates simple math word problems.

/// Why a question has no answer.
pub enum Error
    UnknownOperation
    SyntaxError
    DivisionByZero
end

/// Answers a word problem such as `What is 3 plus 2 multiplied by 3?`,
/// working left to right with no operator precedence.
pub fn answer(question: String) -> Result<Int, Error>
    Some(problem) =
        question
        |> String.strip_prefix("What is")
        |> Maybe.flat_map(&String.strip_suffix(&1, "?"))
    else
        return Err(.UnknownOperation)
    end

    [first, ..rest] = String.words(problem) else return Err(.SyntaxError)
    Some(total) = String.to_int(first) else return Err(.SyntaxError)
    evaluate(total, rest)
end

enum Operation
    Plus
    Minus
    Times
    DividedBy
end

/// Applies each operation in `words` to the running total in turn.
fn evaluate(total: Int, words: List<String>) -> Result<Int, Error>
    case words
        []                           -> Ok(total)
        ["plus", ..rest]             -> operand(total, .Plus, rest)
        ["minus", ..rest]            -> operand(total, .Minus, rest)
        ["multiplied", "by", ..rest] -> operand(total, .Times, rest)
        ["divided", "by", ..rest]    -> operand(total, .DividedBy, rest)
        [word, ..] when String.to_int(word) is Some(_) -> Err(.SyntaxError)
        _ -> Err(.UnknownOperation)
    end
end

/// Reads the number after an operation, applies it and carries on.
fn operand(total: Int, operation: Operation, words: List<String>) -> Result<Int, Error>
    [word, ..rest] = words else return Err(.SyntaxError)
    Some(n) = String.to_int(word) else return Err(.SyntaxError)
    total = apply(operation, total, n)?
    evaluate(total, rest)
end

fn apply(operation: Operation, a: Int, b: Int) -> Result<Int, Error>
    case operation
        .Plus      -> Ok(a + b)
        .Minus     -> Ok(a - b)
        .Times     -> Ok(a * b)
        .DividedBy -> divide(a, b)
    end
end

fn divide(a: Int, b: Int) -> Result<Int, Error>
    if b == 0 then return Err(.DivisionByZero)
    Ok(Int.divide(a, b))
end

// FILE: wordy_test.nomi
import wordy.{self, Error}

test "answers word problems"
    [
        ("just a number", "What is 5?", Ok(5)),
        ("just a zero", "What is 0?", Ok(0)),
        ("just a negative number", "What is -123?", Ok(-123)),
        ("addition", "What is 1 plus 1?", Ok(2)),
        ("addition with a left hand zero", "What is 0 plus 2?", Ok(2)),
        ("addition with a right hand zero", "What is 3 plus 0?", Ok(3)),
        ("more addition", "What is 53 plus 2?", Ok(55)),
        ("addition with negative numbers", "What is -1 plus -10?", Ok(-11)),
        ("large addition", "What is 123 plus 45678?", Ok(45801)),
        ("subtraction", "What is 4 minus -12?", Ok(16)),
        ("multiplication", "What is -3 multiplied by 25?", Ok(-75)),
        ("division", "What is 33 divided by -3?", Ok(-11)),
        ("multiple additions", "What is 1 plus 1 plus 1?", Ok(3)),
        ("addition and subtraction", "What is 1 plus 5 minus -2?", Ok(8)),
        ("multiple subtraction", "What is 20 minus 4 minus 13?", Ok(3)),
        ("subtraction then addition", "What is 17 minus 6 plus 3?", Ok(14)),
        ("multiple multiplication", "What is 2 multiplied by -2 multiplied by 3?", Ok(-12)),
        ("addition and multiplication", "What is -3 plus 7 multiplied by -2?", Ok(-8)),
        ("multiple division", "What is -12 divided by 2 divided by -3?", Ok(2)),
        ("unknown operation", "What is 52 cubed?", Err(Error.UnknownOperation)),
        (
            "Non math question",
            "Who is the President of the United States?",
            Err(.UnknownOperation),
        ),
        ("reject problem missing an operand", "What is 1 plus?", Err(.SyntaxError)),
        ("reject problem with no operands or operators", "What is?", Err(.SyntaxError)),
        ("reject two operations in a row", "What is 1 plus plus 2?", Err(.SyntaxError)),
        ("reject two numbers in a row", "What is 1 plus 2 1?", Err(.SyntaxError)),
        ("reject postfix notation", "What is 1 2 plus?", Err(.SyntaxError)),
        ("reject prefix notation", "What is plus 1 2?", Err(.SyntaxError)),
    ]
    |> subtests (description, question, expected), description
        assert wordy.answer(question) == expected
    end
end

// Not a canonical case: the exercise leaves division by zero open.
test "division by zero"
    assert wordy.answer("What is 1 divided by 0?") == Err(.DivisionByZero)
end
  • The evaluator walks the word list with list patterns, including two-word operators (["multiplied", "by", ..rest]), instead of tokenizing first.
  • Operators are a private Operation enum applied by apply, rather than lambdas passed around.
  • Errors are an Error enum. A number where an operator belongs is a syntax error and any other word is an unknown operation, which is the distinction the canonical cases draw.
  • Division by zero is Error.DivisionByZero, through a check of the divisor and Int.divide, instead of the trap / raises. The canonical data has no such case; the test file adds one, marked as not canonical.
  • Division is its own divide function. if b == 0 then return Err(.DivisionByZero) answers the error, and the check makes b a NonZeroInt below it, so Int.divide(a, b) divides by an Int that cannot be zero and the division cannot trap. Keeping it out of apply keeps each arm there on one line.
  • Guards use binding else ([first, ..rest] = String.words(problem) else { ... }) so the success path stays unindented. The style guide uses a binding else, not Maybe.to_result with ?, when the value is bound for the lines that follow, as every guard here is.
  • The 27 canonical cases are one subtests table.
  • The trailing ? comes off through Maybe.flat_map(&String.strip_suffix(&1, "?")), a capture rather than fn rest -> ....