smartcore
smartcore copied to clipboard
From iterator to Vec should be possible
I'm submitting a
- [x] feature request.
Current Behaviour:
Looks to me that mutable iterators build with Array::iterator_mut
cannot be collected back to a Vec
:
use smartcore::linalg::basic::arrays::Array;
let element_2: &i32 = vec![1, 2, 3].iterator_mut(0).collect::<Vec<i32>>().get(1).unwrap();
println!("mutable iterator: {:?}", *element_2);
This code raise this compiler error:
[E0277] Error: a value of type `Vec<i32>` cannot be built from an iterator over elements of type `&mut {integer}`
╭─[command_48:1:1]
│
21 │ let element_2: &i32 = vec![1, 2, 3].iterator_mut(0).collect::<Vec<i32>>().get(1);
· ───┬───
· ╰───── value of type `Vec<i32>` cannot be built from `std::iter::Iterator<Item=&mut {integer}>`
Maybe we need to implement FromIter
for Vec
? there are any caveats because this should not be possible?
Expected Behaviour:
Should be possible to collect an iterator build from Array::iterator
and Array::iterator_mut
back into a Vec
Hey, I found your machine learning library, gave it a try and it looks awesome! So I went through the issues and thought maybe I can contribute to one or two tickets.
The standard library basically provides three methods for iterating over a collection:
iter()
, which iterates over &T
iter_mut()
, which iterates over &mut T
into_iter()
, which iterates over T
Since Array::iterator
and Array::iterator_mut
cover the first two cases, calling collect::<Vec<i32>>()
won't work since the trait FromIterator<T>
is implemented for Vec<T>
, not for &T so we would have to either implement into_iter()
to move ownership to a new Vec<T>
or simply call collect::<Vec<&T>>
to keep ownership and having references. (Or maybe we can do some tricks by calling clone internally?)
So calling:
let vec = vec![1,2,3].iterator(0).collect::<Vec<&i32>>()
would work and we can get values by simply calling
let elem = vec![1,2,3].iterator(0).collect::<Vec<&i32>>().get(1)
.
thanks for using smartcore
.
we will be glad to take a look to a PR for this or anything else you want to contribute.
P.S. we would like to keep the zero-copy policy when possible.