haskell: 2023 10 parser

This commit is contained in:
Maciej Jur 2023-12-10 16:46:13 +01:00
parent 34b053a229
commit 810f898bf5
Signed by: kamov
GPG key ID: 191CBFF5F72ECAFD
2 changed files with 53 additions and 0 deletions

View file

@ -27,6 +27,7 @@ library
Day07
Day08
Day09
Day10
-- other-modules:

View file

@ -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]]