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 (ie, 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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.