README.md | enso.nim: attempt added for safer Exception handling, README updated to reflect current state and philosophy

This commit is contained in:
buckwheat
2025-12-28 22:31:13 -08:00
parent 8e22fcc169
commit d568c49368
3 changed files with 28 additions and 18 deletions

View File

@ -3,11 +3,13 @@ import std/[options, os, sugar]
# Declarations
type
Error* = enum OK, ERR
IO*[T] = proc(): T
Unit* = object
func attempt*[T](uf: IO[T]): Option[T]
func attempt*(uf: IO[void]): Option[Unit]
func fileread*(file: string): IO[Option[string]]
func filewrite*(data: string, file: string): IO[Error]
func filewrite*(data: string, file: string): IO[Option[Unit]]
func flatmap*[T, U](io: IO[T], fn: T -> IO[U]): IO[U]
func lift*(fn: proc(): void): IO[void]
func lift*[T](fn: proc(): T): IO[T]
@ -20,31 +22,35 @@ func to_IO*[T](val: T): IO[T]
# Unsafe
proc read_unsafe(file: string): Option[string] =
proc unsafe[T](uf: IO[T]): Option[T] =
try:
let data: string = readFile(file)
some(data)
except IOError:
none(string)
let sf: T = uf()
some(sf)
except:
none(T)
proc write_unsafe(data: string, file: string): Error =
proc unsafe(uf: IO[void]): Option[Unit] =
try:
writeFile(file, data)
OK
except IOError:
ERR
run uf
some(Unit())
except:
none(Unit)
# Definitions
func attempt*[T](uf: IO[T]): Option[T] = unsafe(uf)
func attempt*(uf: IO[void]): Option[Unit] = unsafe(uf)
func fileread*(file: string): IO[Option[string]] =
proc(): Option[string] =
if fileExists(file):
read_unsafe(file)
attempt(lift () => readFile(file))
else:
none(string)
func filewrite*(data: string, file: string): IO[Error] =
proc(): Error = write_unsafe(data, file)
func filewrite*(data: string, file: string): IO[Option[Unit]] =
proc(): Option[Unit] = attempt(lift () => writeFile(file, data))
func flatmap*[T, U](io: IO[T], fn: T -> IO[U]): IO[U] = join(map(io, fn))