问题
I'm trying to recursively call a function that copies any type a specified amount of times for example copy 3 'a' would give me ['a','a','a'] while copy 3 2 would give me [2,2,2] This is what I have so far but I'm not sure if my typeline is correct as I think my code should run fine. Can anyone see what's wrong?
copy :: Int->a->[a]
copy x [] = []
copy y a = a:(copy (y-1) a)
edit: updated to this:
copy :: Int->a->[a]
copy 0 a = []
copy y a = [a]++(copy (y-1) a)
However this gives me "aaa" instead of [a,a,a]
回答1:
This is just a suggestion about how to implement your function in a more haskelly way. You are trying to implement standard replicate
function and looking at the standard source code always help. Here is the code for replicate (after simplification)
replicate n x = take n (repeat x)
repeat x = xs where xs = x : xs
The source code is taken from the simplified src returned by lambdabot on haskell irc.
来源:https://stackoverflow.com/questions/19456756/basic-haskell-copying-elements