通过Haskell中的列表进行复制

时间:2018-03-16 09:59:56

标签: list haskell

replicatee :: [a] -> Int -> [a]
replicatee [] _ = []
replicatee xs 0 = []
replicatee (x:xs) n = x:replicatee (x:xs) (n-1): replicatee xs n

所以这是我的代码,用于复制列表中的元素n次,编译器一直显示错误:

Couldnt match type 'a'with [a], I'm seriously confused, please help out.

编辑:我希望我的功能是这样的: replicatee [1,2,3,4] 2

[1,1,2,2,3,3,4,4-]

2 个答案:

答案 0 :(得分:1)

我可能误解了你的意图,但也许你的意思是这样的:

replicatee :: a -> Int -> [a]
replicatee _ 0 = []
replicatee x n = x:replicatee x (n-1)

答案 1 :(得分:0)

replicatee :: [a] -> Int -> [a]
replicatee [] _ = []
replicatee xs 0 = []
replicatee (x:xs) n = x:replicatee (x:xs) (n-1): replicatee xs n

问题是replicatee返回[a]类型的值,但您尝试使用{{1}将其添加到另一个类型[a]列表中}}。从类型检查的角度来看,您需要使用(:) :: a -> [a] -> [a],而不是(++)

(:)

是否你想要的是另一回事。根据您的说明,Mikkel provides the right answer