Menu
Coddy logo textTech

Recap - Safe Calculator

Part of the Logic & Flow section of Coddy's R journey. Lesson 56 of 64.

challenge icon

Challenge

Hard

Complete evaluate(expr). An expression is <number> <operator> <number> with spaces around the operator, such as 8 / 2. Raise errors with stop() for each problem, checked in this order:

  • expected: number operator number when there are not exactly three parts
  • '<part>' is not a number for the first number part that cannot be converted, such as 'x' is not a number
  • unknown operator <op> when the operator is not +, -, * or /
  • division by zero

Otherwise return the result, rounded to four decimal places with round(value, 4).

Then complete run_all(exprs): evaluate each expression inside tryCatch() and return one line per expression, 8 / 2 = 4 or 5 / 0 -> error: division by zero.

The supplied code passes every input line to run_all() and prints each returned line.

Try it yourself

evaluate <- function(expr) {
  # Write your code here
  0
}

run_all <- function(exprs) {
  # Write your code here
  character(0)
}

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(run_all(input), sep = "\n")

All lessons in Logic & Flow

Practice on your own: Online R compiler