问题
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