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

↘锁芯ラ 提交于 2019-12-14 02:11:42

问题


I try to get the word-count example from real-world Haskell running in Frege:

main _ = interact wordCount
    where wordCount input = show (length (lines input)) ++ "\n"

but I get

can't resolve `interact`

Is there a Frege-idiomatic way to do this?


回答1:


It is not in the standard library but you can define something like this:

import Data.List(intercalate)

interact :: (String -> String) -> IO ()
interact f = stdin.getLines >>= println . f . intercalate "\n"

Update (for the comment on Groovy's eachLine):

Frege has try, catch, finally and BufferedReader.getLine that we can use to create such a function:

eachLine :: Reader -> (String -> IO ()) -> IO ()
eachLine reader f = BufferedReader.new reader >>= go where
  go breader = forever (breader.getLine >>= f)
    `catch` (\(e :: EOFException) -> return ())
    `finally` breader.close

try, catch and finally are functions with the following types:

try :: (Applicative γ,Bind γ) => (α->γ β) -> α -> γ β
catch :: Exceptional β => ST γ α -> (β->ST γ α) -> ST γ α
finally :: IO α -> IO β -> IO α

And we can just use catch and finally without try as we have done in eachLine above. Please see this note from Frege source on when try is necessary.



来源:https://stackoverflow.com/questions/18759291/what-is-the-frege-equivalent-to-haskells-interact-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!