I'd like to remove the use of .unwrap()
from code which maps over an ndarray::Array
and use a Result
type for get_data()
instead.
extern crate ndarray;
use ndarray::prelude::*;
use std::convert::TryFrom;
use std::error::Error;
fn get_data() -> Array2<usize> {
// In actual code, "a" comes from an external source, and the type
// is predetermined
let a: Array2<i32> = arr2(&[[1, 2, 3], [4, 5, 6]]);
let b: Array2<usize> = a.map(|x| usize::try_from(*x).unwrap());
b
}
fn main() -> Result<(), Box<dyn Error>> {
let a = get_data();
println!("{:?}", a);
Ok(())
}
For Vec
, I've found this trick: How do I stop iteration and return an error when Iterator::map returns a Result::Err?.
However, this does not work with Array
s (collect
isn't defined, and the semantics don't quite match up, since ndarray::Array
defines a block of primitive types, which (AFAIU) can't hold Result
s).
Is there a nice way to handle this?