开发者

extracting a string into a two-dimensional array?

Consider a string of a2b4g9.

How would I be able to transform it into a two-d开发者_JAVA技巧imensional array of types [(char,int)] like

(a,2)
(b, 4)
(g, 9)

Would I use concat or something else?

How can this be done?


I'd suggest that the easiest way is just to write a recursive function to do it. Something like this should work as long as your numbers never go higher than 9:

toTuple :: String -> [(Char,Int)]

toTuple [] = []
toTuple (letter:reps:rem) = (letter,read [reps]) : toTuple rem

If your numbers do go higher than 9 then it gets a bit more complicated, because the number of repetitions is variable length.

(EDIT: FUZxxl and I posted almost identical solutions around the same time, but that's because it's the obvious answer. I didn't see his post before posting myself)

Another solution is to write a function to take every 2nd element of a list, and then combine the resulting letters and repetitions lists using the zip function.

Or you could go a bit over the top and user a parser combinator like parsec:

import Text.Parsec
import Control.Monad

parseFunc :: String -> String -> Either ParseError [(Char,Int)]

parseFunc = parse (many letterPair)
    where 
        letterPair = do
            l <- letter
            d <- many digit
            return (l, read d)


Try this one:

f :: String -> [(Char,Int)]
f [] = []
f (x:y:zs) = (x,read [y]) : f zs

Or this one:

import Data.List
import Data.Maybe
f :: String -> [(Char,Int)]
f = catMaybes . snd . mapAccumL a Nothing where
  a acc x = maybe (Just x,Nothing) (\acc' -> (Nothing,Just (acc',read [x]))) acc
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜