I am trying to parse user entered string like “A12”, into a Haskell tuple, like (‘A’, 12).
Here’s what I have tried:
import Data.Maybe
type Pos = (Char, Int)
parse :: String -> Maybe Pos
parse u = do
(c, rest) <- (listToMaybe.reads) u
(r, _) <- (listToMaybe.reads) rest
return $ (c, r)
But this always returns Nothing. Why does this happen, and what is the correct way to parse this string? Since this is fairly simple, I’d like to avoid using Parsec or a similar advanced parsing library.
EDIT (to clarify):
Sample Input and Output:
"A12" gives Just ('A', 12)
"J5" gives Just ('J', 5)
"A" gives Nothing
"2324" gives Nothing
readis usually the opposite ofshowand they both generally use Haskell syntax to represent the given values. This means that since the Haskell syntax for characters uses single quotes,showon a character will add single quotes around it, andreadwill expect the single quotes to be there.In other words, your function expects syntax like
'A' 42, and indeed it works if you try that:For your format, I would instead use pattern matching for the first character and then
readsfor the rest, e.g. something like this: