Safe HaskellNone

Day18

Description

General - We kinda need to solve two problems here: We need to parse the expressions and we need to evaluate the expressions.

Looking at the expressions you can see an (binary) abstract syntax tree (AST) where every node is an expression. The (two) children are either a value or an expression again.

To build the AST we first convert the expression string from infix notation to postfix notation (RPN) (with the shunting-yard algorithm (SYA)).

Building the AST from RPN is trivial (Note: We make this easy by reversing the RPN (12+ -> +21)).

To evaluate the AST we just have to (recursively) walk the tree.

Part 1 - Evaluate all expressions and sum up the results.

Part 2 - Now we need to implement precedence (by peeking into the operators stack).

Synopsis

Documentation

data Expression #

All possible expressions.

Instances

Instances details
Eq Expression # 
Instance details

Defined in Day18

Methods

(==) :: Expression -> Expression -> Bool

(/=) :: Expression -> Expression -> Bool

Show Expression # 
Instance details

Defined in Day18

Methods

showsPrec :: Int -> Expression -> ShowS

show :: Expression -> String

showList :: [Expression] -> ShowS

input :: String -> [String] #

Read the input file.

toPostfix :: String -> String #

Convert infix string into postfix (RPN) string (by running the shunting-yard algorithm (SYA)).

toPostfixToken :: String -> String -> String -> String #

Implement SYA (with no prededence; eval left to right)

toPostfixToken' :: String -> String -> (String, String) #

Implement SYA.

toExpression :: String -> Expression #

Turn a postfix/RPN string into an expression AST.

reverse' :: String -> String #

Reverse a/the give expression string (to make the operators asscociate to the left). Note: For this to work we need to flip the parenthis.

eval :: Expression -> Int #

(Recursively) Evaluate an expression.

part1 :: [String] -> Int #

Solve part1.

toPostfix2 :: String -> String #

Same as above, but for part2.

toPostfixToken2 :: String -> String -> String -> String #

Same as above, but for part2 (implementing the precedence of + over *).

part2 :: [String] -> Int #

Solve part2.