Lim H.
Lim H.

Reputation: 10050

Simplify do notation

I'm trying to perform very simple parsing of time string

data Time = Time Int Int Int String

-- example input: 07:00:00AM
timeParser :: Parser Time
timeParser = do
    hh <- digits
    _ <- colon
    mm <- digits
    _ <-colon
    ss <- digits
    p <- period
    return $ Time hh mm ss p

Is there any way to simplify the do block with a combination of (>>) and (>>=) operators?

Upvotes: 2

Views: 170

Answers (2)

Zeta
Zeta

Reputation: 105876

Since your Parser should also be an instance of Applicative:

timeParser :: Parser Time
timeParser = Time <$> (digits <* colon) <*> (digits <* colon) <*> digits <*> period

Upvotes: 12

Erik
Erik

Reputation: 957

By simply tossing out the results of colon, a shortened version of your function (that still uses do-notation) might look something like this:

timeParser :: Parser Time
timeParser = do
  hh <-          digits
  mm <- colon >> digits
  ss <- colon >> digits
  p  <- period
  return $ Time hh mm ss p

Any further desugaring of the do-notation would sacrifice readability.

That being said, I really like Zeta's answer and the applicative style of programming in Haskell floors me.

Upvotes: 3

Related Questions