enso.nim: Added file operations
This commit is contained in:
33
src/enso.nim
33
src/enso.nim
@ -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] =
|
||||
|
||||
Reference in New Issue
Block a user