Skip to content

Instantly share code, notes, and snippets.

@tippenein
Last active August 23, 2016 03:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tippenein/bc86bc912f9ba986ae825c9d1cb9dd49 to your computer and use it in GitHub Desktop.
Save tippenein/bc86bc912f9ba986ae825c9d1cb9dd49 to your computer and use it in GitHub Desktop.
naive timer
import Text.Parsec
type Parser = Parsec String ()
data T = T { hours :: Int, minutes :: Int, seconds :: Int }
instance Show T where
show (T h m s) = show h ++ " hours " ++ show m ++ " minutes " ++ show s ++ " seconds"
parse' :: Parser a -> String -> Either ParseError a
parse' rule = parse rule "(source_file)"
timeP :: Char -> Parser Int
timeP c = option 0 $ try (valParser <* char c)
timeParser :: Parser T
timeParser = do
h <- timeP 'h'
m <- timeP 'm'
s <- timeP 's'
pure $ T h m s
valParser :: Parser Int
valParser = rd <$> many1 digit
where rd = read :: String -> Int
toTime :: String -> T
toTime t = case parse' timeParser t of
Left e -> error (show e)
Right time' -> time'
-- Allows doing simple time parsing
-- toTime "1h23m1s" => 1 hour 23 minutes 1 second
-- allows skipping identifiers
-- toTime "22m20s" => 22 minutes 20 seconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment