enso.nim: Added file operations

This commit is contained in:
buckwheat
2025-12-26 22:18:24 -08:00
parent 996c115a1c
commit e263a216d6
2 changed files with 53 additions and 15 deletions

View File

@ -1,11 +1,14 @@
import std/sugar
import std/[options, os, sugar]
# Declarations
type
Error* = enum OK, ERR
FileDesc* = enum STDIN, STDOUT, STDERR
IO*[T] = proc(): T
func fileread*(file: string): IO[Option[string]]
func filewrite*(data: string, file: string): IO[Error]
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]
@ -15,9 +18,35 @@ func readstr*(stream: FileDesc): IO[string]
func run*[T](io: IO[T]): T
func strput*(str: string): IO[void]
func to_IO*[T](val: T): IO[T]
# Unsafe
proc read_unsafe(file: string): Option[string] =
try:
let data: string = readFile(file)
some(data)
except IOError:
none(string)
proc write_unsafe(data: string, file: string): Error =
try:
writeFile(file, data)
OK
except IOError:
ERR
# Definitions
func fileread*(file: string): IO[Option[string]] =
proc(): Option[string] =
if fileExists(file):
read_unsafe(file)
else:
none(string)
func filewrite*(data: string, file: string): IO[Error] =
proc(): Error = write_unsafe(data, file)
func flatmap*[T, U](io: IO[T], fn: T -> IO[U]): IO[U] = join(map(io, fn))
func lift*(fn: proc(): void): IO[void] =

View File

@ -1,5 +1,5 @@
import enso
import std/[os, strformat, sugar]
import std/[options, strformat, sugar]
proc unsafe_void(str: string) =
echo str
@ -8,13 +8,6 @@ proc unsafe_int(str: string): int =
echo str
result = 1
func check_file(name: string): IO[string] =
proc(): string =
if fileExists(name):
result = readFile(name)
else:
result = "Not found"
func main() =
run strput("Hello from Enso!")
@ -32,13 +25,29 @@ func main() =
name()
let
nested: IO[IO[string]] = get_filename.map(check_file)
joined: IO[string] = nested.join
nested: IO[IO[Option[string]]] = get_filename.map(fileread)
joined: IO[Option[string]] = nested.join
join_opt: Option[string] = joined()
run strput(joined())
if join_opt.isSome:
run strput(join_opt.get)
else:
run strput("joined had no data")
let flat: IO[string] = get_filename.flatmap(check_file)
run strput(flat())
let
flat: IO[Option[string]] = get_filename.flatmap(fileread)
flat_opt: Option[string] = flat()
if flat_opt.isSome:
run strput(flat_opt.get)
else:
run strput("flat had no data")
let writer: Error = run filewrite("Hello world!\n", "test.txt")
if writer == OK:
run strput("Successfully wrote test.txt!")
else:
run strput("Could not write test.txt!")
when isMainModule:
main()