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
import Data.Char
main = myLoop
myLoop = do inp <- getLine
if (inp == "x")
then putStrLn "Bye!"
else do putStrLn(map toUpper inp)
myLoop
However, I can't seem to figure out how to avoid the if (inp == "x")
condition and replace it with an end of stream condition.
In short, I'm looking for Haskell's equivalent to while (cin >> line)
in C++
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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With