praxis

Various programming exercises.
git clone git://git.jtobin.io/praxis.git
Log | Files | Refs

Main.hs (780B)


      1 
      2 module Main where
      3 
      4 import System.Environment
      5 
      6 data Replace a = Replace {
      7     pattern     :: [a]
      8   , replacement :: [a]
      9   }
     10 
     11 stringReplace :: Eq a => [a] -> [a] -> [a] -> [a]
     12 stringReplace pat rep = foldr alg [] where
     13   patLength = length pat
     14   alg c acc
     15     | take patLength (c:acc) == pat = rep ++ drop patLength (c:acc)
     16     | otherwise                     = c : acc
     17 
     18 replace :: Eq a => Replace a -> [a] -> [a]
     19 replace (Replace pat rep) = foldr alg [] where
     20   patLength = length pat
     21   alg c acc
     22     | take patLength (c:acc) == pat = rep ++ drop patLength (c:acc)
     23     | otherwise = c : acc
     24 
     25 main :: IO ()
     26 main = do
     27   args <- getArgs
     28   case args of
     29     (pat:rep:str:_) -> putStrLn (stringReplace pat rep str)
     30     _ -> putStrLn "USAGE: ./stringReplace PATTERN REPLACEMENT STRING"
     31