Mixon
Mixon

Reputation: 33

Multiplying String in a list, Haskell

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

Answers (1)

Michael Kohl
Michael Kohl

Reputation: 66837

  • 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

Upvotes: 1

Related Questions