Day18
Copyright(c) Eric Mertens 2021
LicenseISC
Maintaineremertens@gmail.com
Safe HaskellNone
LanguageHaskell2010

Main

Description

https://adventofcode.com/2021/day/18

Today's problem had us perform manipulations on a tree-based term language. It was made tricky because the problem asked us to do things to the nearest left and right neighbors of elements of our tree.

Synopsis

Documentation

main :: IO () Source #

>>> :main
3551
4555

Snailfish operations

add :: Tree Int -> Tree Int -> Tree Int Source #

Add two expressions and reduce them

reduce :: Tree Int -> Tree Int Source #

Reduce an expression until it won't reduce

unstable :: Tree a -> Maybe (a, a, Zip a) Source #

Find the left-most pair at depth 4.

split :: Tree Int -> Maybe (Tree Int) Source #

Replace the first number with value 10 or more with a pair of it divided in half rounding first down then up.

magnitude :: Tree Int -> Int Source #

Compute the magnitude of an expression

>>> magnitude (parse "[9,1]")
29
>>> magnitude (parse "[[1,2],[[3,4],5]]")
143

Binary trees

data Tree a Source #

A binary tree with data at the leaves

Constructors

(Tree a) :+: (Tree a)

tuple

Leaf a

regular number

Tree zippers

data Side Source #

Marks the side of a tree node constructor that we know the subtree of.

Constructors

L 
R 

type Zip a = [(Side, Tree a)] Source #

A hole in a binary tree. Rebuild the tree with fromZip

fromZip :: Tree a -> Zip a -> Tree a Source #

Rebuild a tree given a zipper and the value to put in the hole.

appUp :: Side -> (Tree a -> Tree a) -> Zip a -> Zip a Source #

Apply the given function to the nearest parent sibling on the given side.

appL :: (a -> a) -> Tree a -> Tree a Source #

Apply a function to the left-most leaf

appR :: (a -> a) -> Tree a -> Tree a Source #

Apply a function to the rightmost leaf

Parsing

parse :: String -> Tree Int Source #

Parse an expression

>>> parse "[[[[0,9],2],3],4]"
(((Leaf 0 :+: Leaf 9) :+: Leaf 2) :+: Leaf 3) :+: Leaf 4

pInt :: ReadP Int Source #

Unsigned Int parser

pTree :: ReadP a -> ReadP (Tree a) Source #

ReadP expression parser