Mojo-Numerics-and-Algorithms-group / NuMojo

NuMojo is a library for numerical computing in Mojo 🔥 similar to numpy in Python.
Apache License 2.0
86 stars 15 forks source link

Implement the __iter__ method to allow an iterator #43

Closed forFudan closed 2 months ago

forFudan commented 2 months ago

Implement the Sized trait to allow len() function. Implement the __iter__ method and struct _NDArrayIter to iterate over the items in an ndarray.

fn main() raises:
    get(4, 4)

fn get(m:Int, n:Int) raises:
    var raw = List[Int32]()
    for _i in range(m*n):
        raw.append(random.randn_float64() * 10)
    var Ac = NDArray(data=raw, shape=List[Int](m,n), order="C")

    for i in Ac:
        print(i, end=" ")

    print(Ac)
    print(str("=") * 50)

Output:

-12 16 13 -9 -16 0 0 -2 5 5 7 -9 -5 1 -3 17 
[[      -12     16      13      -9      ]
 [      -16     0       0       -2      ]
 [      5       5       7       -9      ]
 [      -5      1       -3      17      ]]
Shape: [4, 4]  DType: int32