flix icon indicating copy to clipboard operation
flix copied to clipboard

Console example doesn't handle errors

Open benjamin-thomas opened this issue 1 year ago • 5 comments

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?

benjamin-thomas avatar Oct 08 '24 17:10 benjamin-thomas

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

benjamin-thomas avatar Oct 08 '24 17:10 benjamin-thomas

Thanks @benjamin-thomas, we will take a look!

magnus-madsen avatar Oct 08 '24 17:10 magnus-madsen

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 avatar Oct 09 '24 08:10 JonathanStarup

@JonathanStarup This should be fixed now, right?

magnus-madsen avatar May 21 '25 10:05 magnus-madsen

Because the example is gone or? None of the Console stuff has been fixed.

JonathanStarup avatar May 21 '25 15:05 JonathanStarup