문제

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.

도움이 되었습니까?

해결책

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)

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top