问题
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 bereplicate n x
, notreplicate 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