Multiplying String in a list, Haskell

时光总嘲笑我的痴心妄想 提交于 2020-01-16 09:01:14

问题


I am trying to multiply strings in a list. For instance, when I have a list like ["hello","World"] and I want to 'multiply' it by 2, I want to end up with ["hello","hello","World","World"].

Here's what I came up with:

rep :: Int -> [String] -> [String]
rep n [] = []
rep n [x:xs] = replicate n [x] ++ rep n [xs]

But it gives me exception:

(298,1)-(299,44): Non-exhaustive patterns in function rep

I am totally new to this language and I do not have any ideas how to sort this out. Can you help?


回答1:


  • Your fist problem is that the pattern for non-empty lists is wrong, it should be (x:xs), not [x:xs].
  • Furthermore, replicate expects a single element and turns it into a list of length n, so it should be replicate n x, not replicate n [x].
  • In a similar vain xs is already a list.

If you fix all of this you'll end up with the following, which actually works as intended:

rep :: Int -> [String] -> [String]
rep n [] = []
rep n (x:xs) = replicate n x ++ rep n xs

That said there are many different ways one could write this, for example with concatMap:

rep n = concatMap (replicate n)

or

rep = concatMap . replicate


来源:https://stackoverflow.com/questions/47353797/multiplying-string-in-a-list-haskell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!