Chain Results with Ok and Err Classes

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write classes Ok and Err and a type Result<T, E> that is one or the other. new Ok(value) has ok set to true and a value; new Err(error) has ok set to false and an error. Both have map(fn), which turns an Ok's value with fn into a new Ok and passes an Err on unchanged without calling fn, and unwrapOr(fallback), which gives an Ok's value or, for an Err, the fallback. Type them so that on a Result<T, E>, map's result type follows fn's return type, unwrapOr only takes and returns a T, and checking ok narrows to value or error.

Your code must pass

  • map transforms an Ok
  • map passes an Err on without calling fn
  • unwrapOr gives the value or the fallback
  • Has no type errors
  • map's result type follows the function
  • unwrapOr takes and returns the value type
  • Checking ok narrows to value or error