Search code examples
haskellreplicate

Haskell error with a replicate-like function


I want to write a replicate-like function that works like this :

repli "the" 3 = "ttthhheee" and repli "jason" 4 = "jjjjaaaassssoooonnnn"

Here is the code that I wrote :

myrepli []  n = []
myrepli [x] 0 = []
myrepli [x] n = (x:(myrepli [x] (n-1)))


repli [] n = []
repli (x:xs) n = (myrepli x n) ++ (repli xs n)

The error I get is this :

Couldn't match expected type `[a]' against inferred type `Char'
     Expected type: [[a]]
     Inferred type: [Char]
   In the first argument of `repli', namely `"jason"'
   In the expression: repli "jason" 3

How can I fix this? Thanks.


Solution

  • myrepli is expecting a list and an integer. However, the definition of repli calls it with x, which is an item, not a list of items.

    I imagine you either want to change myrepli to take a single item as argument, or you want to change repli to pass [x] instead of just x. (I would suggest the former rather than the latter.)