Haskell Day 2 — I was Told There Would Be No Math

Fang Jin
1 min readNov 27, 2020

Question: Advent of Code 2015, Day 2

3x11x24
13x5x19
1x9x27
24x8x21
6x8x17

Function

Given a box as string 2x2x2, we can split it as measurements that can be applied to wrapping paper calculation.

type Box = [Char]split :: Box -> [Int]
split "" = []
split s = fp : rest
where parts = break (=='x') s
fp = read (fst parts)::Int
rest = split $ drop 1 $ snd parts
wrapBox :: [Int] -> Int
wrapBox b@(l:w:h:[]) = area + minimum b
where area = sum d * 2
d = zipWith (*) [l, w, h] [w, h, l]

Solution

part1 :: (Foldable t, Functor t) => t Box -> Int
part1 ls = sum $ fmap (wrapBox . split) ls

We leave the part2 to the reader since part2 is very similar to part1 except the wrapping method wrapBox.

Debug

>>> part1 <$> lines <$> getLine
>>> part1 <$> lines <$> readFile "02.input"

--

--

Fang Jin

#OpenToWork Front-end Engineer, book author of “Designing React Hooks the Right Way” sold at Amazon.