Advertisement
Yurry

Алгорифмы

May 8th, 2012
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import System.IO
  2. import System.Environment
  3. import Data.List
  4.  
  5. replace :: String -> String -> String -> String
  6. replace _ _ [] = []
  7. replace src dst s@(x:xs) = case stripPrefix src s of
  8.                                 Just a -> dst ++ replace src dst a
  9.                                 Nothing -> (x:replace src dst xs)
  10.                                
  11. split _ [] = [[]]
  12. split c xs = case span (/= c) xs of
  13.                 (f, []) -> [f]
  14.                 (f, r)  -> (f:split c (tail r))
  15.  
  16. data Rule = Rule {from, to :: String, terminal :: Bool}
  17.     deriving Show
  18. readRule (x:y:z) = Rule {from = x, to = y, terminal = not $ null z}
  19. readRule _ = error "Wrong rule syntax"
  20.  
  21. applyRule rule = replace (from rule) (to rule)
  22.  
  23. main = do args <- getArgs  
  24.           rules <- return (head args) >>= readFile >>= return . map (readRule . split ' ') . lines
  25.           let startStr = args !! 1
  26.           putStrLn $ "0: " ++ startStr
  27.           run 1 rules (args !! 1)
  28.        where run step rules str = putStr (show step ++ ": ") >>
  29.                                   case find ((`isInfixOf` str) . from) rules of
  30.                                        Nothing -> putStrLn "No matching rule, stop."
  31.                                        Just rule -> putStrLn newStr >> if terminal rule
  32.                                                                           then putStrLn "Terminal rule, stop."
  33.                                                                           else run (step + 1) rules newStr
  34.                                                     where newStr = applyRule rule str
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement