Created
November 8, 2015 00:03
-
-
Save savonarola/afc7a80445a2a87042c2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import System.Environment | |
import System.IO | |
import System.IO.Error | |
import Control.Exception | |
withFiles :: [FilePath] -> IOMode -> ([Handle] -> IO a) -> IO a | |
withFiles paths mode f = withFiles' paths mode f [] | |
withFiles' [] mode f handles = do | |
result <- f handles | |
closeFiles handles result | |
withFiles' (path : paths) mode f handles = do | |
handle <- openFile path mode | |
withFiles' paths mode f (handle : handles) | |
closeFiles [] res = do | |
return res | |
closeFiles (handle : handles) res = do | |
hClose handle | |
closeFiles handles res | |
process :: Handle -> [Handle] -> IO () | |
process inHandle outHandles = do | |
process' inHandle outHandles 0 (length outHandles) | |
process' inHandle outHandles cnt totalOut = do | |
input <- try(hGetLine inHandle) | |
case input of | |
Left e -> | |
if isEOFError e | |
then return () | |
else ioError e | |
Right inLine -> | |
do hPutStrLn (outHandles !! (cnt `mod` totalOut)) inLine | |
process' inHandle outHandles (cnt + 1) totalOut | |
main :: IO () | |
main = do | |
args <- getArgs | |
withFiles (tail args) WriteMode (\outHandles -> ( | |
withFiles [head args] ReadMode (\inHandle -> | |
process (head inHandle) outHandles | |
)) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment