= Solution
Separate the maximal decimal prefix from the unconsumed suffix, rejecting an empty prefix:
``
import Data.Char (isDigit, digitToInt)
type Parse a = String -> Maybe (a,String)
parseInt :: Parse Int
parseInt input =
case span isDigit input of
([],_) -> Nothing
(ds,ys) -> Just (foldl (\n d -> 10*n + digitToInt d) 0 ds, ys)
``
The <left fold> uses the <positional notation> recurrence $N_{j+1}=10N_j+d_j$. This parses unsigned decimal operands as illustrated, leaving the first nondigit and everything after it untouched. As the required result type is `Int`, correct mathematical values require the parsed integer to fit that bounded type; arbitrary-length exact values would instead need `Integer` or an explicit <integer overflow> check.
Back to article page