Advertisement
Guest User

Untitled

a guest
Dec 10th, 2018
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. module Main where
  2.  
  3. -- Tree structure. Can be constructed from either a
  4. -- Char (leaves) or another Tree (branches/nodes)
  5. data Tree = Leaf Char | Branch Tree Tree
  6.     deriving (Show)
  7.  
  8. -- Parsing the initial tree construction. Takes a string
  9. -- and returns the final tree and the number of nodes.
  10. -- Recursively builds the tree based on each character
  11. -- in the list.
  12. parse :: [Char] -> (Tree, Int)
  13. parse s
  14.     | c == '*' =
  15.     let (tree0, pos0) = parse (tail s)
  16.         (tree1, pos1) = parse (drop (pos0+1) s)
  17.     in (Branch tree0 tree1, 1 + pos0 + pos1)
  18.     | otherwise = (Leaf c, 1)
  19.     where c = head s
  20.  
  21. stringBuilder :: Tree -> [Char] -> [Char]
  22. stringBuilder t s = snd (decode t s [])
  23.   where
  24.     decode :: Tree -> [Char] -> [Char] -> ([Char], [Char])
  25.     decode (Leaf c)     []     o = ([], [c])
  26.     decode (Leaf c)     is     o =
  27.         let (is',o') = decode t is o in (is', [c] ++ o')
  28.     decode (Branch a b) (i:is) o =
  29.         case i of
  30.             '0' -> decode a is o
  31.             '1' -> decode b is o
  32.             _   -> undefined
  33.     decode (Branch a b) []     o = ([], o)
  34.  
  35. -- Maps each line of input to decode.
  36. lineIterator :: ([Char] -> [Char]) -> [[Char]] -> [Char]
  37. lineIterator func otherLines =
  38.     unlines (map func otherLines)
  39.  
  40. -- Takes the first line of input and builds a tree from it,
  41. -- then returns that with the rest of the input.
  42. splitLines :: [Char] -> (Tree, [[Char]])
  43. splitLines input =
  44.     let everything = lines input
  45.         firstLine = head everything
  46.         otherLines = tail everything
  47.         tree = fst (parse firstLine)
  48.     in (tree, otherLines)
  49.  
  50. -- A secondary main that uses string input and output
  51. -- instead of IO types. Passes the remainder of the input
  52. -- from splitLines and the tree to lineIterator.
  53. secondaryMain :: [Char] -> [Char]
  54. secondaryMain input =
  55.     let (tree, otherLines) = splitLines input
  56.     in lineIterator (stringBuilder tree) otherLines
  57.  
  58. main :: IO()
  59. main = interact secondaryMain
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement