[hs] Clean up 2020_18
This commit is contained in:
parent
1f30a7495b
commit
c29e148001
1 changed files with 8 additions and 19 deletions
|
|
@ -14,44 +14,33 @@ import qualified Text.Megaparsec.Char.Lexer as L
|
||||||
import Aoc.Day
|
import Aoc.Day
|
||||||
import Aoc.Parse
|
import Aoc.Parse
|
||||||
|
|
||||||
data Expr
|
|
||||||
= Lit Int
|
|
||||||
| Add Expr Expr
|
|
||||||
| Mul Expr Expr
|
|
||||||
deriving (Show)
|
|
||||||
|
|
||||||
eval :: Expr -> Int
|
|
||||||
eval (Lit l) = l
|
|
||||||
eval (Add a b) = eval a + eval b
|
|
||||||
eval (Mul a b) = eval a * eval b
|
|
||||||
|
|
||||||
lexeme :: Parser a -> Parser a
|
lexeme :: Parser a -> Parser a
|
||||||
lexeme = L.lexeme (void $ lineWhile isSpace)
|
lexeme = L.lexeme (void $ lineWhile isSpace)
|
||||||
|
|
||||||
symbol :: T.Text -> Parser T.Text
|
symbol :: T.Text -> Parser T.Text
|
||||||
symbol = L.symbol (void $ lineWhile isSpace)
|
symbol = L.symbol (void $ lineWhile isSpace)
|
||||||
|
|
||||||
parser :: [[Operator Parser Expr]] -> Parser [Expr]
|
parser :: [[Operator Parser Int]] -> Parser [Int]
|
||||||
parser table = manyLines expr
|
parser table = manyLines expr
|
||||||
where
|
where
|
||||||
parens = between (symbol "(") (symbol ")")
|
parens = between (symbol "(") (symbol ")")
|
||||||
term = (Lit <$> lexeme L.decimal) <|> parens expr
|
term = lexeme L.decimal <|> parens expr
|
||||||
expr = makeExprParser term table
|
expr = makeExprParser term table
|
||||||
|
|
||||||
table1 :: [[Operator Parser Expr]]
|
table1 :: [[Operator Parser Int]]
|
||||||
table1 = [[InfixL (Add <$ symbol "+"), InfixL (Mul <$ symbol "*")]]
|
table1 = [[InfixL ((+) <$ symbol "+"), InfixL ((*) <$ symbol "*")]]
|
||||||
|
|
||||||
table2 :: [[Operator Parser Expr]]
|
table2 :: [[Operator Parser Int]]
|
||||||
table2 = [[InfixL (Add <$ symbol "+")], [InfixL (Mul <$ symbol "*")]]
|
table2 = [[InfixL ((+) <$ symbol "+")], [InfixL ((*) <$ symbol "*")]]
|
||||||
|
|
||||||
solver :: FilePath -> T.Text -> IO ()
|
solver :: FilePath -> T.Text -> IO ()
|
||||||
solver path text = do
|
solver path text = do
|
||||||
putStrLn ">> Part 1"
|
putStrLn ">> Part 1"
|
||||||
parseAndSolve path text (parser table1) $ print . sum . map eval
|
parseAndSolve path text (parser table1) $ print . sum
|
||||||
|
|
||||||
putStrLn ""
|
putStrLn ""
|
||||||
putStrLn ">> Part 2"
|
putStrLn ">> Part 2"
|
||||||
parseAndSolve path text (parser table2) $ print . sum . map eval
|
parseAndSolve path text (parser table2) $ print . sum
|
||||||
|
|
||||||
day :: Day
|
day :: Day
|
||||||
day = dayText solver
|
day = dayText solver
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue