From 4a331229a2a92fd92e17ee7c7319d036397dffa8 Mon Sep 17 00:00:00 2001 From: chayleaf Date: Fri, 3 Dec 2021 01:50:49 +0700 Subject: [PATCH] day 2 haskell --- hs/02.1.hs | 24 ++++++++++++++++++++++++ hs/02.2.hs | 24 ++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 hs/02.1.hs create mode 100644 hs/02.2.hs diff --git a/hs/02.1.hs b/hs/02.1.hs new file mode 100644 index 0000000..f25ae06 --- /dev/null +++ b/hs/02.1.hs @@ -0,0 +1,24 @@ +import System.IO + +main = do + file <- readFile "../input/02" + let (x, y) = foldl step (0, 0) $ map parse $ lines file + print (x, y, x * y) + +parse s = + case name of + "up" -> Up n + "down" -> Down n + "forward" -> Forward n + where + [name, x] = words s + n = read $ x + +parse :: String -> Action + +data Action = Up Int | Down Int | Forward Int + +step (x, y) (Up n) = (x, y - n) +step (x, y) (Down n) = (x, y + n) +step (x, y) (Forward n) = (x + n, y) +step :: (Int, Int) -> Action -> (Int, Int) diff --git a/hs/02.2.hs b/hs/02.2.hs new file mode 100644 index 0000000..6f36ec2 --- /dev/null +++ b/hs/02.2.hs @@ -0,0 +1,24 @@ +import System.IO + +main = do + file <- readFile "../input/02" + let (a, x, y) = foldl step (0, 0, 0) $ map parse $ lines file + print (x, y, x * y) + +parse s = + case name of + "up" -> Up n + "down" -> Down n + "forward" -> Forward n + where + [name, x] = words s + n = read $ x + +parse :: String -> Action + +data Action = Up Int | Down Int | Forward Int + +step (a, x, y) (Up n) = (a - n, x, y) +step (a, x, y) (Down n) = (a + n, x, y) +step (a, x, y) (Forward n) = (a, x + n, y + a * n) +step :: (Int, Int, Int) -> Action -> (Int, Int, Int)