Home > Blockchain >  Transforming a string into a list of pairs comprising the character from each run together with its
Transforming a string into a list of pairs comprising the character from each run together with its

Time:03-05

So I am required to convert a list of strings to a [(Char,Int)]. So for example, ["xxxxx","yyy"] to [('x',5), ('y',3] . I am able to get the ('x',5) part without any issues but I am not sure how to move on to the next element of the list. Here is my code so far. Any pointers will be greatly appricated.

[(x,y) | let x = head(head(reap xs)), let y = length(head(reap xs)))]

p.s : reap is a function that turns a string into a list of repeated characters. For example "aaaabbbbccc" -> ["aaaa","bbbb","bbb"].

Thanks

CodePudding user response:

I suggest breaking this into smaller parts. First define a function that takes a single String and returns a tuple (Char, Int). Then once you have this function , you can use map to apply it to each String in a list.

CodePudding user response:

You can use the fmap function which applies a function over or any item in the list.
The function charRepetitions accepts a list and uses the charRepetition function to transform an item.

main = do
  _ <- print $ charRepetitions ["xxxxx","yyy"] 
  return ()

charRepetitions :: [String] -> [(Char, Int)]
charRepetitions xs = fmap charRepition xs

charRepetition :: String -> (Char, Int)
charRepetition s = (head s , length s) 
  • Related