Advertisement
Guest User

Untitled

a guest
Jun 22nd, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Data.List
  2.  
  3. data Edit = Change Char
  4.             | Insert Char
  5.             | Copy
  6.             | Delete
  7.             | Kill
  8.     deriving (Show)
  9.  
  10. transform :: String -> String -> [Edit]
  11. transform "" ""                   = []
  12. transform (a:"") (b:"")           = if a == b then [Copy] else [Change b]
  13. transform (a:"") (b:bs)           | a == b = [Copy] ++ transform "" bs
  14.                                   | a == head bs = [Insert b] ++ transform (a:"") bs
  15.                                   | otherwise = [Change b] ++ transform "" bs
  16. transform (a:as) (b:"")           | a == b = [Copy,Kill]
  17.                                   | b == head as = [Delete] ++ transform (tail as) ""
  18.                                   | otherwise = [Change b,Kill]
  19. transform "" (b:"")               = [Insert b]
  20. transform "" (b:bs)               = [Insert b] ++ transform "" bs
  21. transform str1@(a:as) str2@(b:bs) | a == b = [Copy] ++ transform as bs
  22.                                   | a == head bs = [Insert b] ++ transform str1 bs
  23.                                   | b == head as = [Delete] ++ transform (tail as) bs
  24.                                   | otherwise = [Change b] ++ transform as bs
  25.                            
  26. traceTransform :: String -> [Edit] -> String
  27. traceTransform str a = (replicate 16 ' ') ++ str ++ "\n" ++ traceTransformRec str a 0
  28.  
  29. traceTransformRec :: String -> [Edit] -> Int -> String
  30. traceTransformRec _ [] _ = ""
  31. traceTransformRec str (Copy:as) pos = "Copy" ++ (replicate 12 ' ') ++ str ++ "\n" ++ traceTransformRec str as (pos + 1)
  32. traceTransformRec str (Change a:as) pos = let x = replaceNth pos a str
  33.                                           in "Change '" ++ [a] ++ "'" ++ (replicate 6 ' ') ++ x ++ "\n" ++ traceTransformRec x as (pos + 1)
  34. traceTransformRec str (Insert a:as) pos = let x = take pos str ++ [a] ++ drop pos str
  35.                                           in "Insert '" ++ [a] ++ "'" ++ (replicate 6 ' ') ++ x ++ "\n" ++ traceTransformRec x as (pos + 1)
  36. traceTransformRec str (Delete:as) pos = let x = take pos str ++ drop (pos + 1) str
  37.                                           in "Delete" ++ (replicate 10 ' ') ++ x ++ "\n" ++ traceTransformRec x as (pos + 1)
  38. traceTransformRec str [Kill] pos = "Kill" ++ (replicate 12 ' ') ++ take pos str
  39.  
  40. replaceNth :: Int -> a -> [a] -> [a]
  41. replaceNth n newVal (x:xs) | n == 0 = newVal:xs
  42.                            | otherwise = x:replaceNth (n-1) newVal xs
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement