重复列表的元素

use*_*101 0 haskell

我正在写一个小函数重复k lt.它将重复列表中的所有元素k次.

这是我的方法,以下是我试过的代码

repeat 0 xs = xs
repeat k [] = []
repeat k (x:xs)
     |k == 1 = x:repeat 0 xs
     |otherwise = x:repeat (k-1) xs 
Run Code Online (Sandbox Code Playgroud)

然后我意识到我只是将头部移开并将其推回内部.所以我使用 ++运营商?我知道有其他方法可以解决这个问题,但我想学习如何递归,因为它可以通过使用列表推导轻松完成.

请指教.

use*_*465 6

如果你想要递归:

repeat 0 xs     = []
repeat n []     = []
repeat n (x:xs) = x : repeat (n - 1) [x] ++ repeat n xs
Run Code Online (Sandbox Code Playgroud)

repeat 3 [1,2,3]

1 : repeat 2 [1] ++ repeat 3 [2,3]
1 : 1 : repeat 1 [1] ++ repeat 2 [] ++ repeat 3 [2,3]
1 : 1 : 1 : repeat 0 [1] ++ [] ++ repeat 3 [2,3]
1 : 1 : 1 : 2 : repeat 2 [2] ++ repeat 3 [3]
1 : 1 : 1 : 2 : 2 : repeat 1 [2] ++ repeat 2 [] ++ repeat 3 [3]
1 : 1 : 1 : 2 : 2 : 2 : repeat 0 [2] ++ repeat 3 [3]
1 : 1 : 1 : 2 : 2 : 2 : 3 : repeat 2 [3] ++ repeat 3 []
1 : 1 : 1 : 2 : 2 : 2 : 3 : 3 : repeat 1 [3] ++ repeat 2 [] ++ repeat 3 []
1 : 1 : 1 : 2 : 2 : 2 : 3 : 3 : 3 : []
Run Code Online (Sandbox Code Playgroud)

这是丑陋和低效的.这里有更好的解决方案:

repeat' = concatMap . replicate

repeat'' n xs = [x | x <- xs, _ <- [1..n]]

repeat''' n = concat . transpose . replicate n
Run Code Online (Sandbox Code Playgroud)