day7: clean up a bit and add comments

Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
This commit is contained in:
2022-12-07 16:43:56 +05:30
parent a4c25f5d1f
commit 6f152ab365
2 changed files with 33 additions and 21 deletions

View File

@@ -22,32 +22,34 @@ main = do
)
tree
type Filesystem = Tree (String, Int)
tail' :: [a] -> [a]
tail' = drop 1
emptyFs :: String -> Tree (String, Int)
emptyFs :: String -> Filesystem
emptyFs n = Node (n, 0) []
insertFs :: Tree (String, Int) -> String -> Tree (String, Int) -> Tree (String, Int)
insertFs :: Filesystem -> String -> Filesystem -> Filesystem
insertFs (Node n xs) name dir = Node (fst n, snd n + snd (rootLabel dir)) (dir : xs)
totalSize :: [Tree (String, Int)] -> Int
totalSize :: [Filesystem] -> Int
totalSize = sum . map (snd . rootLabel)
ls :: [[String]] -> [Tree (String, Int)]
ls :: [[String]] -> [Filesystem]
ls = map (\[a, b] -> Node (b, read a) []) . filter ((/= "dir") . head)
parse :: [[String]] -> Tree (String, Int) -> Tree (String, Int)
parse :: [[String]] -> Filesystem -> Filesystem
parse input fs = snd $ parse' input fs
parse' :: [[String]] -> Tree (String, Int) -> ([[String]], Tree (String, Int))
parse' :: [[String]] -> Filesystem -> ([[String]], Filesystem)
parse' input fs
| null input || cur !! 1 == "cd" && cur !! 2 == ".." = (tail' input, fs)
| cur !! 1 == "ls" =
| null input || cur == ["$", "cd", ".."] = (tail' input, fs)
| cur == ["$", "ls"] =
let (children, rest) = span ((/= "$") . head) (tail' input)
childFs = ls children
leaves = ls children
name = fst $ rootLabel fs
in parse' rest (Node (name, totalSize childFs) childFs)
in parse' rest (Node (name, totalSize leaves) leaves)
| otherwise =
let name = cur !! 2
(nextInput, newFs) = parse' (tail' input) (emptyFs name)