Search code examples
frege

How to handle exceptions in Frege?


Trying to handle a exception I found a related question talking about this:

what is the Frege equivalent to Haskell's "interact" function?

But it wasn't clear to me how to use the try/catch/finally expressions.

The problem:

I wanted to read a file and return all its lines. In case it didn't exist I may wanted to return an empty list. Something like:

getContent :: String -> IO [String]
getContent filePath = openReader filePath >>= \reader -> reader.getLines
    `catch` (\(e::FileNotFoundException) -> return [])
    `finally` (println "something went wrong")

The previous code compiles but when executed it only shows the following:

frege> getContent "asdf"

java.io.FileNotFoundException: asdf (No such file or directory)

Questions:

  • How should I change my code to act as expected (to return an empty list when the exception is raised) ?
  • Is there any place in the docs related to this ? I'm sure more examples in the docs/wiki/frege goodness would help a lot.

Thanks


Solution

  • The code looks good so far, but there is a problem with the lambda. Like in Haskell, a lambda extends as far right as syntactically possible. Hence, despite catch having lower precedence as >>= it still belongs to the lambda.

    By the way, there is a short-hand form for such lambda expressions:

    _.foo   
    

    is a term that desugars to

    \it -> it.foo
    

    and extra arguments can also be applied:

    _.foo bar baz
    

    gets desugared to

    \it -> it.foo bar baz
    

    This is exactly made for situations like above.

    In the REPL you can get documentation on catch, finally and >>= with the :help command.

    You are right that this would be a nice issue for Frege Goodness. However, there are also working examples in the github repo. For this case, look at examples/SimpleIO.fr