Skip to content

Instantly share code, notes, and snippets.

@ijt
Created June 28, 2011 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ijt/1050213 to your computer and use it in GitHub Desktop.
Save ijt/1050213 to your computer and use it in GitHub Desktop.
Haskell program to demux input
#!/usr/bin/env runhaskell
import System.Environment
import System.Exit
import System.IO
usage = "usage: cat somefile | demux outfile1 outfile2 ..."
help = "This program alternates sending its input to outfile1 and outfile2."
main = do
args <- getArgs
case args of
["-h"] -> doHelp
["--help"] -> doHelp
[] -> doUsage
[_] -> doUsage
_ -> do
outfiles <- mapM (\path -> openFile path WriteMode) args
contents <- getContents
demux outfiles . lines $ contents
mapM_ hClose outfiles
doUsage = do
putStrLn usage
exitFailure
doHelp = do
putStrLn usage
putStrLn help
exitSuccess
demux :: [Handle] -> [String] -> IO ()
demux outfiles lines =
zipWithM_ hPutStrLn (cycle outfiles) lines
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment