Search code examples
parsinghaskellrefactoringtrifecta

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?


Solution

  • Use count.

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