Reputation: 33
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?
Upvotes: 0
Views: 392
Reputation: 66837
(x:xs)
, not [x:xs]
.n
, so it should be replicate n x
, not replicate n [x]
. 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
Upvotes: 1