Alex Gyoshev
Alex Gyoshev

Reputation: 11977

Most concise way to parse a three-digit number in Haskell (Trifecta)

What is the idiomatic way parse three consecutive digits into a string?

The following works, but does not scale:

threeDigits :: Parser Int
threeDigits = do
    d1 <- digit
    d2 <- digit
    d3 <- digit
    return (digitToInt d1 * 100 + digitToInt d2 * 10 + digitToInt d3)

More generally, how can this scale for N numbers?

Upvotes: 1

Views: 334

Answers (1)

Alex Gyoshev
Alex Gyoshev

Reputation: 11977

Use count.

digits :: Int -> Parser Int
digits n = read <$> count n digit

Upvotes: 1

Related Questions