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

前端 未结 4 1664
予麋鹿
予麋鹿 2020-12-22 05:23

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

相关标签:
4条回答
  • 2020-12-22 06:01
    Hugs> map (\(c,n) -> replicate n c) [('a',9), ('b',10)]
    ["aaaaaaaaa","bbbbbbbbbb"]
    

    or

    map (uncurry $ flip replicate)
    
    0 讨论(0)
  • 2020-12-22 06:07

    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.

    0 讨论(0)
  • 2020-12-22 06:10

    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.

    0 讨论(0)
  • 2020-12-22 06:14

    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.

    0 讨论(0)
提交回复
热议问题