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

[lib] Use AnyLifeTime to explicitly indicate the lifetime of iterator #60

Closed forFudan closed 2 months ago

forFudan commented 2 months ago

PR #43 introduced iterator of NDArray. Due to ASAP destruction of the variables, the array is destroyed after the last use, meaning that the user to manually call it after the iterator to extend its lifetime. Otherwise, there is a dangling pointer.

var A = nm.NDArray(10, random=True)
for i in A: 
    print(i, end="\t")  # dangling pointer! Unexpected printing results.
var _ = A^  # Force A's lifetime to be extended to here.

This is now fixed by using built-in AnyLifetime type to explicitly indicate the lifetime of the pointer.

Test code:

import numojo as nm

fn main() raises:
    test[nm.i8](10)
    test[nm.f64](20)

fn test[dtype: DType](length: Int) raises:
    var A = nm.NDArray[dtype](length, random=True)
    print(A)
    print("Iterate over the array:")
    for i in A:
        print(i, end="\t")
    print()
    print(str("=") * 30)

Test results:

[       14      97      -59     ...     -40     66      -2      ]
Shape: [10]  DType: int8
Iterate over the array:
14      97      -59     -4      112     -94     -48     -40     66      -2
==============================

[       0.56038992815200594     0.80956665342737133     0.51171255280046901     ...     0.77284646408542756     0.19185895447404114     0.78036676197514943     ]
Shape: [20]  DType: float64
Iterate over the array:
0.56038992815200594     0.80956665342737133     0.51171255280046901     0.99508454830702531     0.96661136330079034     0.42605082744229772     0.65299872691067640.96153310957578975      0.85798733908715086     0.29402614920162445     0.41464457882825878     0.51489290517673014     0.78978453202871557     0.544272801735292580.093629911904999585    0.43225952539313756     0.84492743866956055     0.77284646408542756     0.19185895447404114     0.78036676197514943
==============================