Guest User

Untitled

a guest
Dec 13th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. module Day9 where
  2.  
  3. import Control.Applicative
  4. import Text.Megaparsec
  5. import Text.Megaparsec.String
  6. import Data.Tree
  7. import Data.Monoid
  8. import Data.Maybe
  9. import Control.Monad (void)
  10. import Text.Printf
  11.  
  12.  
  13. fooP :: Parser (Tree (Maybe String))
  14. fooP =
  15. garbageP <|> groupP
  16.  
  17. garbageP :: Parser (Tree (Maybe String))
  18. garbageP = do
  19. void $ char '<'
  20. Node . Just . catMaybes <$> manyTill (ignoreP <|> Just <$> anyChar) (char '>') <*> return []
  21. where
  22. ignoreP = char '!' >> anyChar >> return Nothing
  23.  
  24. groupP :: Parser (Tree (Maybe String))
  25. groupP = do
  26. void $ char '{'
  27. things <- fooP `sepBy` char ','
  28. void $ char '}'
  29. return $ Node Nothing things
  30.  
  31. score :: Tree (Maybe t) -> Tree Int
  32. score =
  33. score' 1
  34. where
  35. score' n (Node v ch) =
  36. case v of
  37. Nothing -> Node n (map (score' (n + 1)) ch)
  38. Just _ -> Node 0 (map (score' n) ch)
  39.  
  40. run :: IO ()
  41. run = do
  42. input <- readFile "data/day9"
  43. let res = parse fooP "day9" input
  44. case res of
  45. Left e -> print e
  46. Right r -> do
  47. printf "Sum of scores is %d\n" (getSum . foldMap Sum $ score r)
  48. printf "Sum of garbage lengths is %d\n" (getSum . fromJust . foldMap (fmap Sum) $ fmap (fmap length) r)
Add Comment
Please, Sign In to add comment