From 810f898bf5a035f116c947b60bbc3e74ea1eb20e Mon Sep 17 00:00:00 2001 From: Maciej Jur Date: Sun, 10 Dec 2023 16:46:13 +0100 Subject: [PATCH] haskell: 2023 10 parser --- 2023/haskell/aoc2023.cabal | 1 + 2023/haskell/solutions/Day10.hs | 52 +++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 2023/haskell/solutions/Day10.hs diff --git a/2023/haskell/aoc2023.cabal b/2023/haskell/aoc2023.cabal index 6102620..fbae9a8 100644 --- a/2023/haskell/aoc2023.cabal +++ b/2023/haskell/aoc2023.cabal @@ -27,6 +27,7 @@ library Day07 Day08 Day09 + Day10 -- other-modules: diff --git a/2023/haskell/solutions/Day10.hs b/2023/haskell/solutions/Day10.hs new file mode 100644 index 0000000..a9dff0c --- /dev/null +++ b/2023/haskell/solutions/Day10.hs @@ -0,0 +1,52 @@ +{-# LANGUAGE OverloadedStrings #-} +module Day10 where + +import Data.Void (Void) +import Data.Text (Text) +import Data.Char (isSpace) +import Data.Bifunctor (first) +import Text.Megaparsec (Parsec, errorBundlePretty, runParser, many, eof, satisfy) +import Text.Megaparsec.Char (newline) + + +data Pipe = E | S | UD | LR | UL | UR | DL | DR + deriving Show + +data Dir = L | R | U | D + +type Row = Int +type Col = Int + +type Parser = Parsec Void Text + + +input :: Text +input = + ".....\n\ + \.S-7.\n\ + \.|.|.\n\ + \.L-J.\n\ + \.....\n" + +parse :: Text -> Either String [[Pipe]] +parse = first errorBundlePretty . runParser grid "" + where + pipe :: Char -> Pipe + pipe c = case c of + '.' -> E + 'S' -> S + '|' -> UD + '-' -> LR + 'J' -> UL + 'L' -> UR + '7' -> DL + 'F' -> DR + bad -> error $ "Invalid character: " <> [bad] + row :: Parser [Pipe] + row = map pipe <$> many (satisfy $ not . isSpace) <* newline + grid :: Parser [[Pipe]] + grid = many row <* eof + +-- >>> parse input +-- Right [[E,E,E,E,E],[E,S,LR,DL,E],[E,UD,E,UD,E],[E,UR,LR,UL,E],[E,E,E,E,E]] +