简体   繁体   中英

Converting a string of characters into a list with a set layout in Haskell

I've got the following function to enlarge, it takes a string such as "5a" and it outputs in a list, ie [('a',5)] . How could I change it so that it allows the input of more than just 1 pair, so if something like "5a5b" was input, the output would be [('a',5),('b',5)] ?

The current code that I have for this is here:

enlarge :: String -> [(Char,Int)]
enlarge [] = []
enlarge xs = [(a,b) | (b,a:_) <- reads xs]

The code above works and it will work for just one pair, ie if "5a" is input, it will output [('a',5)] . However, I'd like to change it so that it will allow more than just one pair, ie if "5a3b" is input, the output should be [('a',5),('b',3)] . Currently, it only takes into consideration the first 2 parts of the string.

My attempt at doing this is here:

enlarge xs = [((a,b),ts) | ((b,a),ts) <- reads xs, reads ts]

And what i'm trying to do here, is first get the pair for the first two characters, and then read any more characters and then do the same to those.

I wrote a recursive code for your request.

enlarge :: String -> [(Char,Int)]
enlarge [] = []
enlarge (x:y:ls) = [(y,digitToInt x)] ++ enlarge ls

Here, the code assumes that the input length is even. And used digitToInt to convert the Char to Int.

We need more input-output examples. For example what should happen to "12z" ? Also it is not really clear what reads means. But I think you want this

[(c, read i :: Int) | [i, c] <- chunksOf 2 xs]

Don't forget to import chunksOf , which can be found in Data.List.Split .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM