From 664cc4f6f86f7672cff433bfa551d2c3e78dcf45 Mon Sep 17 00:00:00 2001 From: Amneesh Singh Date: Mon, 5 Dec 2022 19:38:51 +0530 Subject: [PATCH] day2: update - use implement ordering like normal people Signed-off-by: Amneesh Singh --- day2.hs | 62 ++++++++++++++++++------------------------------------- flake.nix | 22 ++++++++++---------- 2 files changed, 31 insertions(+), 53 deletions(-) diff --git a/day2.hs b/day2.hs index 18687af..7dffd24 100644 --- a/day2.hs +++ b/day2.hs @@ -2,54 +2,32 @@ main :: IO () main = do - input <- readFile "day2.in" + choices <- parse <$> readFile "day2.in" putStr "Q1: " - print $ q1 input + print $ q1 choices putStr "Q2: " - print $ q2 input + print $ q2 choices data Choice = Rock | Paper | Scissors deriving (Enum, Eq) -q1 :: String -> Int -q1 = - sum - . map - ( \[x, _, y] -> - let i = val x 'A' - j = val y 'X' - in fromEnum j + 1 + case () of - _ - | i == j -> 3 - | winCond i == j -> 6 - | otherwise -> 0 - ) - . lines +instance Ord Choice where + compare x y | x == y = EQ + compare Rock Paper = LT + compare Paper Scissors = LT + compare Scissors Rock = LT + compare _ _ = GT -q2 :: String -> Int -q2 = - sum - . map - ( \[x, _, y] -> - let i = val x 'A' - j = val y 'X' - in 1 + case fromEnum j of - 0 -> 0 + fromEnum (loseCond i) - 1 -> 3 + fromEnum i - 2 -> 6 + fromEnum (winCond i) - ) - . lines +parse :: String -> [(Choice, Choice)] +parse = map (\[x, _, y] -> (val x 'A', val y 'X')) . lines + +score :: (Choice, Choice) -> Int +score (i, j) = 1 + fromEnum j + 3 * fromEnum (compare j i) + +q1 :: [(Choice, Choice)] -> Int +q1 = sum . map score + +q2 :: [(Choice, Choice)] -> Int +q2 = sum . map (score . \(i, j) -> (i, toEnum $ mod (fromEnum i + fromEnum j + 2) 3)) val :: Char -> Char -> Choice val a b = toEnum (fromEnum a - fromEnum b) :: Choice - -winCond :: Choice -> Choice -winCond c = case c of - Rock -> Paper - Paper -> Scissors - Scissors -> Rock - -loseCond :: Choice -> Choice -loseCond c = case c of - Paper -> Rock - Scissors -> Paper - Rock -> Scissors diff --git a/flake.nix b/flake.nix index 9391a9b..ddc1b54 100644 --- a/flake.nix +++ b/flake.nix @@ -13,18 +13,18 @@ pkgs = import nixpkgs { inherit system; }; + src = ./.; in - { - devShells = with pkgs; rec { - default = mkShell { - buildInputs = [ ghc ]; - }; - withLsp = mkShell { - buildInputs = [ - ghc - haskell-language-server - ]; - }; + with pkgs; { + devShells.default = mkShell { + buildInputs = [ + ghc + haskell-language-server + ]; + }; + apps.default = { + type = "app"; + program = "${ghc}/bin/runhaskell"; }; } );