Question

For a test app, I'm trying to convert a special type of string to a tuple. The string is always in the following format, with an int (n>=1) followed by a character.

Examples of Input String:

"2s"

"13f"

"1b"

Examples of Desired Output Tuples (Int, Char):

(2, 's')

(13, 'f')

(1, 'b')

Any pointers would be extremely appreciated. Thanks.

Was it helpful?

Solution

You can use readS to parse the int and get the rest of the string:

readTup :: String -> (Int, Char)
readTup s = (n, head rest)
  where [(n, rest)] = reads s

a safer version would be:

maybeReadTup :: String -> Maybe (Int, Char)
maybeReadTup s = do
  [(n, [c])] <- return $ reads s
  return (n, c)

OTHER TIPS

Here's one way to do it:

import Data.Maybe (listToMaybe)

parseTuple :: String -> Maybe (Int, Char)
parseTuple s = do
  (int, (char:_)) <- listToMaybe $ reads s

  return (int, char)

This uses the Maybe Monad to express the possible parse failure. Note that if the (char:_) pattern fails to match (i.e., if there is only a number with no character after it), this gets translated into a Nothing result (this is due to how do notation works in Haskell. It calls the fail function of the Monad if pattern matches fail. In the case of Maybe a, we have fail _ = Nothing). The function also evaluates to Nothing if reads can't read an Int at the beginning of the input. If this happens, reads gives [] which is then turned into Nothing by listToMaybe.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top