Console example doesn't handle errors
Hello!
The InputOutput example fails if I enter ctrl-d for example (I studied this example because I wanted to understand how could I consume stdin)
I found 2 workarounds:
def runWithConsole(f: Unit -> t \ ef + InputOutput): Result[String, t] \ ef + IO = {
try Ok(f()) with InputOutput {
def read(k) = {
try k(System.console().readLine())
catch {
case _: NullPointerException => Err("Console is not available")
}
}
def write(s, k) = {
println(s);
k()
}
}
}
Or change the API and do something like this:
def runWithConsole(f: Unit -> t \ ef + MyConsole): Result[String, t] \ ef + IO = {
let scanner = new Scanner(System.in);
try Ok(f()) with MyConsole {
def read(k) =
let input =
if (scanner.hasNextLine())
Some(scanner.nextLine())
else
None;
k(input)
def write(s, k) = {
println(s);
k()
}
}
}
Could you clarify how error handling should be done?
Or probably something in between would be more fitting
def runWithConsole(f: Unit -> t \ ef + MyConsole): Result[String, t] \ ef + IO = {
let scanner = new Scanner(System.in);
try Ok(f()) with MyConsole {
def read(k) =
if (scanner.hasNextLine())
k(scanner.nextLine())
else
Err("EOF")
def write(s, k) = {
println(s);
k()
}
}
}
It'd be nice to improve the example to demonstrate idiomatic error handling
Thanks @benjamin-thomas, we will take a look!
I think - other than a practical issue about nullpointer - there is also a question of whether the Flix effect Console represents a console like System.console or whether it represents stdin/out. I believe that StdIn can be defined when System.console is not, if you pipe input and things like that.
I'd vote, that since Console doesn't have other terminal like capabilities, and is really just input output, then we should use standard in/out directly.
@JonathanStarup This should be fixed now, right?
Because the example is gone or? None of the Console stuff has been fixed.