aoc

advent of code
git clone git://source.orangerot.dev:/aoc.git
Log | Files | Refs

Test.hs (1094B)


      1 import Data.Char (isDigit, isSpace)
      2 
      3 data Color = Red | Green | Blue deriving (Show, Eq)
      4 
      5 -- Parse a single digit
      6 digit :: Char -> Maybe Int
      7 digit c
      8   | isDigit c = Just (read [c])
      9   | otherwise = Nothing
     10 
     11 -- Parse an integer
     12 -- Parse an integer
     13 parseInt :: String -> Maybe Int
     14 parseInt str = case reads str of
     15   [(num, "")] -> Just num
     16   _           -> Nothing
     17 
     18 -- Parse color
     19 parseColor :: String -> Maybe Color
     20 parseColor "red"   = Just Red
     21 parseColor "green" = Just Green
     22 parseColor "blue"  = Just Blue
     23 parseColor _       = Nothing
     24 
     25 -- Parse the entire input string
     26 parseInput :: String -> Maybe Bool
     27 parseInput input = do
     28   let (numStr, rest) = span (\c -> isDigit c ) input
     29   num <- parseInt numStr
     30   let colorStr = dropWhile isSpace rest
     31   color <- parseColor colorStr
     32   case color of
     33     Red   -> pure (num < 12)
     34     Green -> pure (num < 13)
     35     Blue  -> pure (num < 14)
     36 
     37 main :: IO ()
     38 main = do
     39   putStrLn "Enter input (e.g., '10 red'):"
     40   input <- getLine
     41   case parseInput input of
     42     Just result -> putStrLn $ "Result: " ++ show result
     43     Nothing     -> putStrLn "Invalid input."