必须使用与复制函数相同的效果来编写函数。
我的尝试:
rep list = [ a | a <- list, _ <- [1..a]]
与Ints合作很好,但我也希望将它与chars一起使用。 像这样:
rep 4 "Hello" => "Hello", "Hello", "Hello", "Hello"
2递归:
rep :: (Num i, Ord i) => i -> a -> [a]
rep n x
| n <= 0 = []
| otherwise = x:rep (n-1) x
与字符相同的问题!
答案 0 :(得分:2)
对于列表理解,这应该有效:
rep :: (Enum a, Num a) => a -> t -> [t]
rep num list = [ a | a <- [list], _ <- [1..num]]
或者以更高效和更好的形式(感谢@chi):
rep num list = [ list | _ <- [1..num]]
演示:
λ> rep 3 3
[3,3,3]
λ> rep 3 "hello"
["hello","hello","hello"]
在这两种情况下,你的递归程序都适用于我。