Begin Day 4, implement parser master
authorJack Kinsey <j.jameskinsey@gmail.com>
Tue, 4 Dec 2018 05:47:54 +0000 (00:47 -0500)
committerJack Kinsey <j.jameskinsey@gmail.com>
Tue, 4 Dec 2018 05:47:54 +0000 (00:47 -0500)
day04/guards.hs [new file with mode: 0644]

diff --git a/day04/guards.hs b/day04/guards.hs
new file mode 100644 (file)
index 0000000..a46e06d
--- /dev/null
@@ -0,0 +1,45 @@
+import qualified Data.Map.Strict as M
+import Text.ParserCombinators.ReadP 
+import Control.Applicative ((<|>))
+
+main :: IO ()
+main = do
+    shifts <- map parse . lines <$> getContents
+    print "a"
+
+type GID = Int
+
+data Status = Begin | Awake | Asleep deriving (Show)   
+data Date = Date Int Int Int deriving (Show)
+data Time = Time Int Int deriving (Show)
+
+data Shift = Shift Status GID Date Time deriving (Show)
+
+parse :: String -> Shift
+parse = fst . head . readP_to_S go
+    where digit :: ReadP Char
+          digit = satisfy (\char -> char >= '0' && char <= '9')
+          stGet :: String -> Status
+          stGet "wakes up" = Awake
+          stGet "falls asleep" = Asleep
+          stGet "Guard #" = Begin
+          go :: ReadP Shift
+          go = do
+            char '['
+            year <- read <$> count 4 digit
+            char '-'
+            month <- read <$> count 2 digit
+            char '-'
+            day <- read <$> count 2 digit
+            char ' '
+            hour <- read <$> count 2 digit
+            char ':'
+            minute <- read <$> count 2 digit
+            string "] "
+            rt <- string "Guard #" <|> string "wakes up" <|> string "falls asleep"
+            gid <- option (-1) (read <$> many1 digit)
+            optional $ string " begins shift"
+            eof
+            let d = Date year month day
+            let t = Time hour minute
+            return (Shift (stGet rt) gid d t)