Ahsan
Ahsan

Reputation: 787

How to convert a list of (Char,Int) to a string with the given number of repeated chars?

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 example the input [(a,9),(b,10)] should give ["aaaaaaaaa","bbbbbbbbbb"] as output.

Upvotes: 0

Views: 2901

Answers (4)

Dan Burton
Dan Burton

Reputation: 53675

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.

Upvotes: 0

John L
John L

Reputation: 28097

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.

Upvotes: 3

sepp2k
sepp2k

Reputation: 370172

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.

Upvotes: 2

Fred Foo
Fred Foo

Reputation: 363597

Hugs> map (\(c,n) -> replicate n c) [('a',9), ('b',10)]
["aaaaaaaaa","bbbbbbbbbb"]

or

map (uncurry $ flip replicate)

Upvotes: 5

Related Questions