diff --git a/src/enso.nim b/src/enso.nim index 5d28e00..e15ccd5 100644 --- a/src/enso.nim +++ b/src/enso.nim @@ -10,7 +10,7 @@ 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] func join*[T](io: IO[IO[T]]): IO[T] -func map*[T, U](io: IO[seq[T]], fn: T -> U): IO[seq[U]] +func map*[T, U](io: IO[T], fn: T -> U): IO[U] func readstr*(stream: FileDesc): IO[string] func run*[T](io: IO[T]): T func strput*(str: string): IO[void] @@ -18,7 +18,7 @@ func to_IO*[T](val: T): IO[T] # Definitions -func flatmap*[T, U](io: IO[T], fn: T -> IO[U]): IO[U] = join(io.map(fn)) +func flatmap*[T, U](io: IO[T], fn: T -> IO[U]): IO[U] = join(map(io, fn)) func lift*(fn: proc(): void): IO[void] = proc(): void = fn() @@ -26,21 +26,10 @@ func lift*(fn: proc(): void): IO[void] = func lift*[T](fn: proc(): T): IO[T] = proc(): T = fn() -func join*[T](io: IO[IO[T]]): IO[T] = io.map(run) +func join*[T](io: IO[IO[T]]): IO[T] = map(io, run) -func map*[T, U](io: IO[seq[T]], fn: T -> U): IO[seq[U]] = - proc(): seq[U] = - let list: seq[T] = io() - - if list.len == 0: - @[] - else: - let - head: T = list[0] - tail: seq[T] = list[1..^1] - new: IO[seq[T]] = to_IO tail - - @[fn(head)] & run new.map(fn) +func map*[T, U](io: IO[T], fn: T -> U): IO[U] = + proc(): U = fn(run(io)) func readstr*(stream: FileDesc): IO[string] = case stream: diff --git a/tests/test.nim b/tests/test.nim index 98173ed..d7b1d5c 100644 --- a/tests/test.nim +++ b/tests/test.nim @@ -1,5 +1,5 @@ import enso -import std/[strformat, sugar] +import std/[os, strformat, sugar] proc unsafe_void(str: string) = echo str @@ -8,7 +8,12 @@ proc unsafe_int(str: string): int = echo str result = 1 -func add_two(x: int): int = x + 2 +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!") @@ -20,15 +25,20 @@ func main() = out_void() run strput(fmt"{out_int()}") + let get_filename: IO[string] = + proc(): string = + let name: IO[string] = readstr(STDIN) + echo "Enter the file name:" + name() + let - num_list: IO[seq[int]] = to_IO @[1, 2, 3, 4, 5] - list_added: IO[seq[int]] = num_list.map(add_two) + nested: IO[IO[string]] = get_filename.map(check_file) + joined: IO[string] = nested.join - run strput(fmt"{list_added()}") + run strput(joined()) - run strput("Enter a string") - let read: IO[string] = readstr(STDIN) - run strput(read()) + let flat: IO[string] = get_filename.flatmap(check_file) + run strput(flat()) when isMainModule: main()