~/bend-docscommunity

io.bend source

io.bend on the hub · documented module

# bend-ndarray's files: .npy arrays loaded and saved with Base's File effects (npy.bend does the encoding).#   import bend-ndarray@<version>/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 Baseimport ./shape.bend as Simport ./ndarray.bend as NPimport ./npy.bend as NPYdef 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<Result<&1, &1, S.NdErr, NP.ND>>:        x : Unit <- File.close(f)        return NPY.from_npy(bs)    case Tuple{f, Fail{Tuple{c, why}}}:      do IO<Result<&1, &1, S.NdErr, NP.ND>>:        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<Result<&1, &1, S.NdErr, NP.ND>>:        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 pathdef load(+path: String) -> IO(Result<&1, &1, S.NdErr, NP.ND>):  do IO<Result<&1, &1, S.NdErr, NP.ND>>:    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<Result<&1, &1, S.NdErr, Unit>>:        x : Unit <- File.close(f)        return Done{Unit{}}    case Tuple{f, Fail{Tuple{c, why}}}:      do IO<Result<&1, &1, S.NdErr, Unit>>:        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<Result<&1, &1, S.NdErr, Unit>>:        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<Result<&1, &1, S.NdErr, Unit>>:    r : Result<&1, &1, U32 & String, File> <- File.open(path, "w")    opened_w(r, path, NPY.to_npy(a))