# bend-ndarray's files: .npy arrays loaded and saved with Base's File effects (npy.bend does the encoding). # import bend-ndarray@/io.bend as NIO # r : Result<&1, &1, S.NdErr, NP.ND> <- NIO.load("a.npy") # w : Result<&1, &1, S.NdErr, Unit> <- NIO.save("b.npy", a) import Base import ./shape.bend as S import ./ndarray.bend as NP import ./npy.bend as NPY def read_done(r: File & Result<&1, &1, U32 & String, List<&2, U32>>, +path: String) -> IO(Result<&1, &1, S.NdErr, NP.ND>): match r: case Tuple{f, Done{+bs}}: do IO>: x : Unit <- File.close(f) return NPY.from_npy(bs) case Tuple{f, Fail{Tuple{c, why}}}: do IO>: x : Unit <- File.close(f) return Fail{S.FileErr{"cannot read " ++ path ++ ": " ++ why}} def opened_r(r: Result<&1, &1, U32 & String, File>, +path: String) -> IO(Result<&1, &1, S.NdErr, NP.ND>): match r: case Done{f}: do IO>: x : File & Result<&1, &1, U32 & String, List<&2, U32>> <- File.read_bytes(f, 4294967295) read_done(x, path) case Fail{Tuple{c, why}}: IO.pure(Result<&1, &1, S.NdErr, NP.ND>, Fail{S.FileErr{"cannot open " ++ path ++ ": " ++ why}}) # the array in the .npy file at path def load(+path: String) -> IO(Result<&1, &1, S.NdErr, NP.ND>): do IO>: r : Result<&1, &1, U32 & String, File> <- File.open(path, "r") opened_r(r, path) def write_done(r: File & Result<&1, &1, U32 & String, Unit>, +path: String) -> IO(Result<&1, &1, S.NdErr, Unit>): match r: case Tuple{f, Done{u}}: do IO>: x : Unit <- File.close(f) return Done{Unit{}} case Tuple{f, Fail{Tuple{c, why}}}: do IO>: x : Unit <- File.close(f) return Fail{S.FileErr{"cannot write " ++ path ++ ": " ++ why}} def opened_w(r: Result<&1, &1, U32 & String, File>, +path: String, bs: List<&2, U32>) -> IO(Result<&1, &1, S.NdErr, Unit>): match r: case Done{f}: do IO>: x : File & Result<&1, &1, U32 & String, Unit> <- File.write_bytes(f, bs) write_done(x, path) case Fail{Tuple{c, why}}: IO.pure(Result<&1, &1, S.NdErr, Unit>, Fail{S.FileErr{"cannot open " ++ path ++ ": " ++ why}}) # a written to path as a .npy file (version 1.0, its dtype, little-endian, C order) def save(+path: String, a: NP.ND) -> IO(Result<&1, &1, S.NdErr, Unit>): do IO>: r : Result<&1, &1, U32 & String, File> <- File.open(path, "w") opened_w(r, path, NPY.to_npy(a))