How can I convert [(char,Int)]
to a String of the Int in the second component gives the number of repetitions of the character in the first component? For examp
Hugs> map (\(c,n) -> replicate n c) [('a',9), ('b',10)]
["aaaaaaaaa","bbbbbbbbbb"]
or
map (uncurry $ flip replicate)
I'm assuming the input is supposed to be [('a', 9), ('b', 10)]
since without the '
s it would only make sense if a
and b
were previously defined, which you did not mention.
In that case you can use replicate
to create a list which contains a given element a given number of times (note that the string "aaaaaaaaaa"
is a list containing the element 'a'
9 times). To do that for every tuple in the list, you can use map
on the list. Now you have a list containing the strings for each character. To turn that into a single string separated by commas, you can use intercalate
, which takes a separator and a list of lists and returns a single li.
The facetious and horrible answer:
Prelude> let replignore ((_,x):[]) = [replicate x 'b']; replignore ((_,x):xs) = replicate x 'a' : replignore xs
Prelude> replignore [(a,9),(b,10)]
<interactive>:1:13: Not in scope: `a'
<interactive>:1:19: Not in scope: `b'
Prelude> let a = undefined
Prelude> let b = undefined
Prelude> replignore [(a,9),(b,10)]
["aaaaaaaaa","bbbbbbbbbb"]
But it didn't quite fit the specs since it includes the quotation marks in the answer. ;)
My point is, you need quotes around your Char
and String
literals.
This can be assembled from just a few functions in the Prelude. Since your input is a list of tuples, the return value becomes a list of strings.
repChars :: (Char, Int) -> String
repChars (c,n) = replicate n c
Prelude> map repChars [('a',9),('b',10)]
["aaaaaaaaa","bbbbbbbbbb"]
Or if you want to do it as a point-free one-liner:
repCharList = map (uncurry (flip replicate))
Is this homework? If so, please use the homework tag.