Advertisement
Kekker_

working!

Dec 10th, 2018
315
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. {-
  2.  - Author: Calvin Williams, cwilliams2016@my.fit.edu
  3.  - Course: CSE 4250, Fall 2017
  4.  - Project: Proj4, Decoding Text
  5.  - Language implementation:
  6.  -}
  7.  
  8. module Main where
  9.  
  10. -- Tree structure. Can be constructed from either a
  11. -- Char (leaves) or another Tree (branches/nodes)
  12. data Tree = Leaf Char | Branch Tree Tree
  13.     deriving (Show)
  14.  
  15. -- Parsing the initial tree construction. Takes a string
  16. -- and returns the final tree and the number of nodes.
  17. -- Recursively builds the tree based on each character
  18. -- in the list.
  19. parse :: [Char] -> (Tree, Int)
  20. parse s
  21.     | c == '*' =
  22.     let (tree0, pos0) = parse (tail s)
  23.         (tree1, pos1) = parse (drop (pos0+1) s)
  24.     in (Branch tree0 tree1, 1 + pos0 + pos1)
  25.     | otherwise = (Leaf c, 1)
  26.     where c = head s
  27.  
  28. -- Recursively builds the string by concatenating each
  29. -- decode call onto the next and dropping each number
  30. -- used
  31. stringBuilder :: Tree -> [Char] -> [Char]
  32. stringBuilder t s
  33.     | s == [] = []
  34.     | otherwise =   let c  = fst (decode t s)
  35.                         xs = snd (decode t s)
  36.                     in c ++ (stringBuilder t xs)
  37.  
  38. -- Recursively builds the output string by traversing
  39. -- the tree built in parse.
  40. decode :: Tree -> [Char] -> ([Char], [Char])
  41. decode (Leaf c)     (x:xs) = ([c], x:xs)
  42. decode (Leaf c)       []   = ([c], [])
  43. decode (Branch a b) (x:xs) =
  44.     case x of
  45.         '0' -> decode a xs
  46.         '1' -> decode b xs
  47.         _   -> undefined
  48. decode (Branch a b)   []   = ([], [])
  49.  
  50. -- Maps each line of input to decode.
  51. lineIterator :: ([Char] -> [Char]) -> [[Char]] -> [Char]
  52. lineIterator func otherLines =
  53.     unlines (map func otherLines)
  54.  
  55. -- Takes the first line of input and builds a tree from it,
  56. -- then returns that with the rest of the input.
  57. splitLines :: [Char] -> (Tree, [[Char]])
  58. splitLines input =
  59.     let everything = lines input
  60.         firstLine = head everything
  61.         otherLines = tail everything
  62.         tree = fst (parse firstLine)
  63.     in (tree, otherLines)
  64.  
  65. -- A secondary main that uses string input and output
  66. -- instead of IO types. Passes the remainder of the input
  67. -- from splitLines and the tree to lineIterator.
  68. secondaryMain :: [Char] -> [Char]
  69. secondaryMain input =
  70.     let (tree, otherLines) = splitLines input
  71.     in lineIterator (stringBuilder tree) otherLines
  72.  
  73. main :: IO()
  74. main = interact secondaryMain
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement