Having trouble with recursion and Type mismatching in Haskell
-- 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)开发者_StackOverflow社区)
*** 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.
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)
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.
精彩评论