|
| 1 | +{-# LANGUAGE NoImplicitPrelude #-} |
| 2 | + |
1 | 3 | module AdventOfCode.Year2020.Day18 |
2 | 4 | ( main, |
3 | 5 | partOne, |
4 | 6 | partTwo, |
5 | 7 | ) |
6 | 8 | where |
7 | 9 |
|
8 | | -import AdventOfCode.Input (parseInput) |
9 | | -import AdventOfCode.TH (inputFilePath) |
10 | | -import Control.Applicative ((<|>)) |
11 | | -import Control.Monad.Combinators.Expr |
12 | | -import Text.Trifecta (Parser, natural, parens, some, symbol) |
| 10 | +import AdventOfCode.Input (parseString, rawInputAoC) |
| 11 | +import AdventOfCode.Puzzle |
| 12 | +import AdventOfCode.TH (defaultMainPuzzle) |
| 13 | +import Control.Monad.Combinators.Expr (Operator (InfixL), makeExprParser) |
| 14 | +import Relude |
| 15 | +import Text.Trifecta (Parser, natural, parens, symbol) |
13 | 16 |
|
14 | 17 | main :: IO () |
15 | | -main = |
16 | | - do |
17 | | - putStr "Part One: " |
18 | | - print =<< partOne |
19 | | - putStr "Part Two: " |
20 | | - print =<< partTwo |
21 | | - |
22 | | -partOne :: IO Int |
23 | | -partOne = sum <$> parseInput (some expr) $(inputFilePath) |
24 | | - where |
25 | | - expr = makeExprParser (parens expr <|> posInt) [[addition, multiplication]] |
| 18 | +main = $(defaultMainPuzzle) |
| 19 | + |
| 20 | +partOne :: SimplePuzzle String Integer |
| 21 | +partOne = solve [[multiplication, addition]] |
| 22 | + |
| 23 | +partTwo :: SimplePuzzle String Integer |
| 24 | +partTwo = solve [[addition], [multiplication]] |
| 25 | + |
| 26 | +getInput :: IO String |
| 27 | +getInput = rawInputAoC 2020 18 |
26 | 28 |
|
27 | | -partTwo :: IO Int |
28 | | -partTwo = sum <$> parseInput (some expr) $(inputFilePath) |
| 29 | +solve :: [[Operator Parser Integer]] -> SimplePuzzle String Integer |
| 30 | +solve table = ask >>= parseString (some expr) <&> sum |
29 | 31 | where |
30 | | - expr = makeExprParser (parens expr <|> posInt) [[addition], [multiplication]] |
| 32 | + expr = makeExprParser (parens expr <|> natural) table |
31 | 33 |
|
32 | | -addition :: Operator Parser Int |
33 | | -addition = InfixL ((+) <$ symbol "+") |
| 34 | +addition :: (Num a) => Operator Parser a |
| 35 | +addition = binary "+" (+) |
34 | 36 |
|
35 | | -multiplication :: Operator Parser Int |
36 | | -multiplication = InfixL ((*) <$ symbol "*") |
| 37 | +multiplication :: (Num a) => Operator Parser a |
| 38 | +multiplication = binary "*" (*) |
37 | 39 |
|
38 | | -posInt :: Parser Int |
39 | | -posInt = fromInteger <$> natural |
| 40 | +binary :: String -> (a -> a -> a) -> Operator Parser a |
| 41 | +binary name f = InfixL (f <$ symbol name) |
0 commit comments