Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read until end of stream in haskell

Tags:

haskell

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++

like image 333
K Mehta Avatar asked Mar 17 '12 23:03

K Mehta


3 Answers

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
like image 177
Carl Avatar answered Oct 03 '22 17:10

Carl


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
like image 19
dave4420 Avatar answered Oct 20 '22 04:10

dave4420


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.

like image 10
Daniel Lyons Avatar answered Oct 20 '22 05:10

Daniel Lyons