Basic stdin/stdout programs in Haskell

It is not very complicated to write basic stdin/stdout Unix-style programs in Haskell. For example, the following one-line program copies stdin to stdout.

main = interact id

This might not look very useful, but this code is a good starting point to implement, for example, Unix-style filter programs. When you look at the definition of interact, you get ideas about adding additional logic.

interact f = do s <- getContents
   putStr (f s)

For example, a filter that does a line-based transformation for each line in stdin and writes the transformed lines to stdout, might look as follows.

main = do
   contents <- getContents
   let ls = lines contents
       lst = map transformLine ls
       str = unlines lst
   putStr str

As you can see, Haskell already comes with some nice functions to handle lines in text-files. See Tutorials/Programming Haskell/String IO in the Haskell wiki for some more inspiration.

Comment