1 line simple cat in Haskell
Tom Moertel
tom@moertel.com
14 Nov 2002 17:33:59 -0500
On Wed, 2002-11-13 at 22:43, William Lee Irwin III wrote:
> There is a semantic difference here, as the version I posted above takes
> files from the command-line, though it does fail to accommodate the
> pass-through case, which is handled by: [...]
I need this behavior often enough to justify writing a small module to
provide it:
Full version at http://tea.moertel.com/~thor/ravt/ravt-0.9/GetInput.hs
-- GetInput.hs
-- Tom Moertel <tom@moertel.com>
-- CVS $Id: GetInput.hs,v 1.1 2002/09/09 04:57:23 thor Exp $
-- | This module provides a method of getting input from files named
-- on the command line or, if no files are provided, from standard
-- input. This mimics Perl's default input handling, which is
-- convenient. Also, the module provides versions of the standard
-- 'interact' function that use these input-getting behaviors.
module GetInput ( getInputDefault, getInputFromArgs
, interactDefault, interactFromArgs) where
import Control.Monad (liftM)
import System.Environment (getArgs)
-- | Reads the arguments passed on the command line and then passes
-- them to 'getInputFromArgs' for handling.
getInputDefault :: IO String
getInputDefault = getArgs >>= getInputFromArgs
-- | Treats the input list as a list of files from which to read
-- input sequentially. If the list is empty, input is read from
-- standard input. If "-" is passed as a file, it is taken to
-- mean standard input.
getInputFromArgs :: [String] -> IO String
getInputFromArgs [] = getContents
getInputFromArgs xs = liftM concat (mapM readFromFile xs)
where
readFromFile "-" = getContents
readFromFile file = readFile file
-- | Gets input via 'getInputDefault', processes it with the
-- function argument @f@, and then prints the @String@ that
-- @f@ returns.
interactDefault :: (String -> String) -> IO ()
interactDefault f = getInputDefault >>= putStrLn . f
-- | Gets input via 'getInputFromArgs', processes it with the
-- function argument @f@, and then prints the @String@ that
-- @f@ returns.
interactFromArgs :: [String] -> (String -> String) -> IO ()
interactFromArgs args f
= getInputFromArgs args >>= putStrLn . f