[Haskell-cafe] short yet featureful grep

John Meacham john at repetae.net
Thu Apr 27 18:39:34 EDT 2006

my favorite example is the featureful yet short grep, supporting quite a
few non-trivial options as well as a detailed '--help' message. :)

this is a great example for anyone that says strong typing clutters code
:) Haskell can be much more concise as well as safer than perl given the
right libraries.

main = do
        (fs,(verb,c,e,o,q)) <- getOptions (
                "v|verbose" ?? "set verbose mode"
                "c" ?? "count occurances",
                "e" ==> "." ?? "the pattern to match",
                "o" ?? "show just the match rather than the line"'
                "q" ?? "just tell whether it matches"
        when verb $ putStrLn ("reading " ++ show fs)
        ls <- fmap (lines . concat) $ mapM readFiles fs
        when q $ if any (=~ e) ls then exit 0 else exit 1
        when c $ print $ sum (map (fromEnum . (=~ e)) ls)
        flip mapM ls $ \l -> case (l =~ e) of
                Nothing -> return ()
                Just xs -> putStrLn $ if o then xs else l


John Meacham - ⑆repetae.net⑆john⑈

More information about the Haskell-Cafe mailing list