0
-- genrep
 genrep :: a -> Int -> [a]
 genrep a n 
    | n == 0 = []
    |otherwise = a ++ genrep (a (n-1))

So I'm trying to make a simple replication function in haskell - one that would take a generic type a and replicate it n times. However, the above does not seem to work. I keep getting this error code:

*** Expression     : a ++ genrep (a (n - 1))
*** Term           : genrep (a (n - 1))
*** Type           : Int -> [b]
*** Does not match : [a]

Can anyone tell me what's going on? The function looks correct to me, but Haskell doesn't seem to like this.

2 Answers 2

4

Change this:

| otherwise = a ++ genrep (a (n-1))

to this:

| otherwise = [a] ++ genrep a (n-1)

Your current version calls genrep recursively with only one argument when it expects two. The extra parenthesis aren't required.

Edit: I fixed up the above code to include the [a] instead of just a. Sorry about that. This is actually what I'd suggest you do:

genrep :: a -> Int -> [a]
genrep a 0 = []
genrep a n = a : genrep a (n-1)
Sign up to request clarification or add additional context in comments.

2 Comments

Hmm... that doesn't work. I get another error complaining about an infinite type unification with that.
@Waffles [a] ++ is rather pointless, just use a :. The first makes a single element into a list then performs a concatenation of two lists, the second is just the list constructor to cons an element onto an existing list. OJ probably used the first form to closely match what you already had.
2

You can also write it:

genrep :: a -> Int -> [a]
genrep a n = take n (repeat a)

Or even:

genrep = flip replicate

Since replicate exists: http://hackage.haskell.org/packages/archive/base/latest/doc/html/src/GHC-List.html#replicate

If you don't know its name, you can find it by using this Hoogle search: http://www.haskell.org/hoogle/?hoogle=a+-%3E+Int+-%3E+%5Ba%5D

Usually you don't have to write this kind of recursion by hand, you can reuse functions like take or repeat.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.