For now this applies to Haskell only, and it may turn out to be tricky for the Rust implementation. In practice, the limitation hasn't turned out to be important, and we could even go the other way and use `Integer` everywhere. This does however at least help with debugging, as well as just being conceptually right. The `nil` and `(/\)` functions are intended to be overloaded to work for other list-like things in a later commit, and from there we will investigate using `OverloadedLists` and `RebindableSyntax` to recover standard list syntax, although there are probably limitations due to `(:)` being special.
53 lines
1.6 KiB
Haskell
53 lines
1.6 KiB
Haskell
module Puzzles.Day1 (puzzle) where
|
|
|
|
import Pre
|
|
|
|
puzzle :: Puzzle
|
|
puzzle =
|
|
Puzzle
|
|
{ number = 1
|
|
, parser = const $ ((,) <$> ((char 'L' $> L) <|> (char 'R' $> R)) <*> (Inc <$> decimal)) `sepEndBy` newline
|
|
, parts =
|
|
( sum
|
|
. ( flip evalState 50
|
|
. traverse \(d, i) -> do
|
|
modify $ snd . step i d
|
|
p' <- get
|
|
pure $ Count if p' == 0 then 1 else 0
|
|
)
|
|
)
|
|
/\ ( sum
|
|
. flip evalState 50
|
|
. traverse \(d, i) -> do
|
|
p <- get
|
|
c <- state $ step i d
|
|
p' <- get
|
|
pure case d of
|
|
R -> abs c
|
|
L ->
|
|
if
|
|
| p == 0 -> abs c - 1
|
|
| p' == 0 -> abs c + 1
|
|
| otherwise -> abs c
|
|
)
|
|
/\ nil
|
|
, extraTests = mempty
|
|
}
|
|
|
|
data Direction = L | R
|
|
deriving (Eq, Ord, Show)
|
|
|
|
newtype Pos = Pos Int
|
|
deriving newtype (Eq, Ord, Show, Num)
|
|
|
|
newtype Inc = Inc Int
|
|
deriving newtype (Eq, Ord, Show, Num)
|
|
|
|
newtype Count = Count Int
|
|
deriving newtype (Eq, Ord, Show, Num)
|
|
|
|
step :: Inc -> Direction -> Pos -> (Count, Pos)
|
|
step (Inc i) d (Pos p) = bimap Count Pos case d of
|
|
L -> (p - i) `divMod` 100
|
|
R -> (p + i) `divMod` 100
|