-
Notifications
You must be signed in to change notification settings - Fork 0
/
2b.hs
33 lines (27 loc) · 799 Bytes
/
2b.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoImplicitPrelude #-}
import AOC
main :: IO ()
main = interact $ f . parseList p
data Direction = Up | Down | Forward deriving (Show, Eq, Read, Ord, Bounded, Enum)
p :: Parser (Direction, Int)
p = do
d <- enump
char ' '
n <- integer
pure (d, n)
f :: Foldable t => t (Direction, Int) -> Int
f xs = x * y
where
(x, y) = evalState (foldM move (0, 0) xs) 0
-- Making it a bit more complicated than necessary to get the hang of MonadState. Alternative solution of 2a with (,,)
move :: (Num a, MonadState a m) => (a, a) -> (Direction, a) -> m (a, a)
move (x, y) (Up, i) = do
modify (subtract i)
pure (x, y)
move (x, y) (Down, i) = do
modify (+ i)
pure (x, y)
move (x, y) (Forward, i) = do
aim <- get
pure (x + i, y + i * aim)