-
Notifications
You must be signed in to change notification settings - Fork 19
Description
I would like to demonstrate a potential approach to construct views of array. This approach does not requires creation of an extra struct NDArrayView
. The view itself is a special case of NDArray
. All methods applied to NDArray
applies to NDArrayView
. Thus, we do not need to bother adding tons of permutations of operations between NDArray
and NDArrayView
.
In order to achieve this, we just need to add one layer of container which holds the underlying data buffer. When the container is type OwnedData
, it is NDArray
as we know. When the container is type RefData
, it is the view of array.
struct NDArray[dtype: DType, Buffer: Bufferable = OwnedData](): # define struct
NDArray[DType.float64, OwnedData] # This is normal array
NDArray[DType.float64, [RefData[__origin_of(self)]] # This is a view of array
Rust also uses this general approach, though the detailed implementation might be different.
pub type Array<A, D> = ArrayBase<OwnedRepr<A>, D>
I made an example Matrix16 type to demonstrate it. Because parameterized traits are not supported yet by Mojo, I use Float16
as the underlying data type. The relevant code is located in the branch arrayview
:
https://github.com/Mojo-Numerics-and-Algorithms-group/NuMojo/tree/arrayview/docs/internal
matrix16.mojo
defines this demo matrix type.matrix16test.mojo
contains some tests.
You can run the files to see the effects.
Let's discuss on this approach. If you find this approach good, we can apply it on NDArray
type in future, when parameterized traits are supported by Mojo.
I wrote another blog on this topic, in case you are interested.