2015-10-05 42 views
3

試圖處理一個例外,我發現了一個相關的問題談論這個:如何處理Frege中的異常?

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

但它不是我清楚如何使用try/catch/finally表達式。

問題

我想讀一個文件,並返回其所有行。如果它不存在,我可能想要返回一個空的列表。喜歡的東西:

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

上面的代碼編譯,但在執行時只顯示以下內容:

frege> getContent "asdf" 

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

問題:

  • 我應該如何改變我的代碼充當預期(在引發異常時返回空列表)?
  • 在與此相關的文檔中是否有任何地方?我相信docs/wiki/frege goodness中的更多示例會有很大幫助。

感謝

+0

準確地說,將lambda表達式更改爲_.getLines使其工作:-) –

回答

2

的代碼看起來不錯,到目前爲止,但與拉姆達的問題。就像在Haskell中一樣,lambda擴展儘可能在語法上是可能的。因此,儘管catch的優先級低於>>=,它仍屬於lambda。

順便提一下,有這樣的lambda表達式的短手形式:

_.foo 

是desugars到

\it -> it.foo 

和也可以應用額外的參數的一個術語:

_.foo bar baz 

GET desugared to

\it -> it.foo bar baz 

這是針對上述情況的。

在REPL中,您可以獲取關於catch的文檔,最後和>> = with:help命令。

你說得對,這對弗雷格善良來說是個不錯的問題。但是,github回購中也有工作示例。對於這種情況,請看示例/ SimpleIO.fr