Read until end of stream in haskell

前端 未结 4 1014
别那么骄傲
别那么骄傲 2021-02-14 00:13

I\'m fairly new to Haskell, and I\'d like to keep reading lines from the console until the end of the stream, and outputting everything I get in upper case. So far, I\'ve got

相关标签:
4条回答
  • 2021-02-14 00:27

    This goes way beyond what you're really asking for, but I use this pattern a lot: interact:

    myFun :: String -> String
    myFun = ...
    
    main = interact (unlines . myFun . lines)
    

    Your function myFun will be executed against every line of standard input and the result sent to standard output.

    0 讨论(0)
  • 2021-02-14 00:28

    You could also just rely on lazy IO.

    import Data.Char
    
    main :: IO ()
    main = do
       inp <- getContents
       let ls = lines inp
           upcased = map (map toUpper) ls
       mapM_ putStrLn upcased
    
    0 讨论(0)
  • 2021-02-14 00:29

    Another option is to use when whose documentation can be found here:

    import System.IO (isEOF)
    import Data.Char (toUpper)
    import Control.Monad (forever, when)
    import System.Exit (exitSuccess)
    main = myLoop
    
    myLoop = forever $ do
                    done <- isEOF
                    when done $ putStrLn "Bye!" >> exitSuccess
                    inp <- getLine
                    putStrLn (map toUpper inp)
                    myLoop
    

    Otherwise, the answer is identical to the one by @dave4420.

    0 讨论(0)
  • 2021-02-14 00:50

    Use isEOF from System.IO.

    import System.IO (isEOF)
    import Data.Char
    
    main = myLoop
    
    myLoop = do done <- isEOF
                if done
                  then putStrLn "Bye!"
                  else do inp <- getLine
                          putStrLn (map toUpper inp)
                          myLoop
    
    0 讨论(0)
提交回复
热议问题