day2: update - use implement ordering like normal people

Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
This commit is contained in:
2022-12-05 19:38:51 +05:30
parent 4c74b44b0d
commit 664cc4f6f8
2 changed files with 31 additions and 53 deletions

62
day2.hs
View File

@@ -2,54 +2,32 @@
main :: IO () main :: IO ()
main = do main = do
input <- readFile "day2.in" choices <- parse <$> readFile "day2.in"
putStr "Q1: " putStr "Q1: "
print $ q1 input print $ q1 choices
putStr "Q2: " putStr "Q2: "
print $ q2 input print $ q2 choices
data Choice = Rock | Paper | Scissors deriving (Enum, Eq) data Choice = Rock | Paper | Scissors deriving (Enum, Eq)
q1 :: String -> Int instance Ord Choice where
q1 = compare x y | x == y = EQ
sum compare Rock Paper = LT
. map compare Paper Scissors = LT
( \[x, _, y] -> compare Scissors Rock = LT
let i = val x 'A' compare _ _ = GT
j = val y 'X'
in fromEnum j + 1 + case () of
_
| i == j -> 3
| winCond i == j -> 6
| otherwise -> 0
)
. lines
q2 :: String -> Int parse :: String -> [(Choice, Choice)]
q2 = parse = map (\[x, _, y] -> (val x 'A', val y 'X')) . lines
sum
. map score :: (Choice, Choice) -> Int
( \[x, _, y] -> score (i, j) = 1 + fromEnum j + 3 * fromEnum (compare j i)
let i = val x 'A'
j = val y 'X' q1 :: [(Choice, Choice)] -> Int
in 1 + case fromEnum j of q1 = sum . map score
0 -> 0 + fromEnum (loseCond i)
1 -> 3 + fromEnum i q2 :: [(Choice, Choice)] -> Int
2 -> 6 + fromEnum (winCond i) q2 = sum . map (score . \(i, j) -> (i, toEnum $ mod (fromEnum i + fromEnum j + 2) 3))
)
. lines
val :: Char -> Char -> Choice val :: Char -> Char -> Choice
val a b = toEnum (fromEnum a - fromEnum b) :: 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

View File

@@ -13,18 +13,18 @@
pkgs = import nixpkgs { pkgs = import nixpkgs {
inherit system; inherit system;
}; };
src = ./.;
in in
{ with pkgs; {
devShells = with pkgs; rec { devShells.default = mkShell {
default = mkShell { buildInputs = [
buildInputs = [ ghc ]; ghc
}; haskell-language-server
withLsp = mkShell { ];
buildInputs = [ };
ghc apps.default = {
haskell-language-server type = "app";
]; program = "${ghc}/bin/runhaskell";
};
}; };
} }
); );