module Commons where import Data.String.Utils import System.IO import Text.Read data Round = Round { red :: Int, green :: Int, blue :: Int } data Game = Game { gid :: Int, rounds :: [Round] } parseCubes :: [String] -> Round -> Round parseCubes [] round = round parseCubes ([h, ' ', 'r', 'e', 'd']: t) round = parseCubes t round {red = read [h]} parseCubes ([h1, h2, ' ', 'r', 'e', 'd']: t) round = parseCubes t round {red = read [h1, h2]} parseCubes ([h, ' ', 'g', 'r', 'e', 'e', 'n']: t) round = parseCubes t round {green = read [h]} parseCubes ([h1, h2, ' ', 'g', 'r', 'e', 'e', 'n']: t) round = parseCubes t round {green = read [h1, h2]} parseCubes ([h, ' ', 'b', 'l', 'u', 'e']: t) round = parseCubes t round {blue = read [h]} parseCubes ([h1, h2, ' ', 'b', 'l', 'u', 'e']: t) round = parseCubes t round {blue = read [h1, h2]} parseRound :: String -> Round parseRound roundRaw = parseCubes (split ", " roundRaw) Round {red = 0, green = 0, blue = 0} parseRounds :: String -> [Round] parseRounds roundsRaw = map parseRound (split "; " roundsRaw) parseGame :: String -> Game parseGame ('G': 'a': 'm': 'e': ' ': h: ':': ' ': t) = Game {gid = read [h], rounds = parseRounds t} parseGame ('G': 'a': 'm': 'e': ' ': h1: h2: ':': ' ': t) = Game {gid = read [h1, h2], rounds = parseRounds t} parseGame ('G': 'a': 'm': 'e': ' ': h1: h2: h3: ':': ' ': t) = Game {gid = read [h1, h2, h3], rounds = parseRounds t} parseGame (_: t) = parseGame t parse :: IO [Game] parse = do done <- isEOF if done then return [] else do line <- getLine let game = parseGame line otherGames <- parse return (game: otherGames)