ndarray icon indicating copy to clipboard operation
ndarray copied to clipboard

Checked Subtract Support

Open benburk opened this issue 4 years ago • 2 comments

Running the following code...

let z: Array1<u32> = arr1(&[1,0,1]) - arr1(&[0,1,0]);

...causes a panic with attempt to subtract with overflow'

Would it be possible to get support for something such as

let z: Array1<u32> =  arr1(&[1,0,1]).checked_sub(arr1(&[0,1,0])).unwrap();

or is there an alternative approach one can suggest?

benburk avatar Dec 10 '21 17:12 benburk

we discussed wrapping here: https://github.com/rust-ndarray/ndarray/pull/1107#issuecomment-974896229 also needs a design, so nothing implemented yet. I guess this is a bit of a similar issue, yet it needs a quite different solution.

What's the use case here? What motivates wanting a checked_sub if you unwrap it?

bluss avatar Dec 10 '21 17:12 bluss

The code is just for illustrative purposes. In actuality, it gives one the ability to handle the Option however one likes, as in any other usage of the regular checked_sub. In my specific case, I was looking to do something like this

let z: HashMap<Array2<u32>, u32> = my_hashmap
            .into_iter()
            .map(|(k, v): (Array2<u32>, u32)| (k.checked_sub(state), v))
            .flatten()
            .collect();

If you could propose a clean alternative, perhaps by comparing the two arrays before doing the subtraction, that would be appreciated!

benburk avatar Dec 10 '21 17:12 benburk