Skip to content

Instantly share code, notes, and snippets.

@ajiyoshi
Last active December 11, 2015 08:09
Show Gist options
  • Save ajiyoshi/4571530 to your computer and use it in GitHub Desktop.
Save ajiyoshi/4571530 to your computer and use it in GitHub Desktop.
-- 元はこれ https://github.com/haruyama/Haskell.Sample/blob/master/CommandLine/mygrep/Main.hs
-- ライセンス:https://github.com/haruyama/Haskell.Sample/blob/master/CommandLine/mygrep/LICENSE
import System.Environment
import System.IO
import System.Exit
import Control.Monad (filterM)
import qualified Data.Text as T
import qualified Data.Text.ICU.Regex as TIR
import qualified Data.Text.IO as TIO
-- getContents は一度に全部読み込んだりしないと聞いたので、私ならこう書くかな的な。
mainloop' :: TIR.Regex -> Handle -> IO ()
mainloop' reg inh = do
c <- TIO.hGetContents inh
matched <- filterM (matchesLine reg) $ T.lines c
mapM_ TIO.putStrLn matched
main :: IO ()
main = do
args <- getArgs
if length args < 2
then do
hPutStrLn stderr "Usage: mygrep pattern file1 file2 ..."
exitWith (ExitFailure 1)
else do
reg <- TIR.regex [] (T.pack . head $ args)
mapM_ (\fn -> withFile fn ReadMode (mainloop' reg)) $ drop 1 args
exitSuccess
matchesLine:: TIR.Regex -> T.Text -> IO Bool
matchesLine reg line = do
TIR.setText reg line
TIR.find reg 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment