我想创建一个带有列表的函数,并使用[[e1],[e1,e2],[e1,e2,e3]...]
形式创建列表推导列表。
例如:
f5 ['a','b','c'] = ["a","ab","abc"]
f5 [1,2,3] = [[1],[1,2],[1,2,3]]
我的代码:
f5 xs = [a | a <- xs]
-- tests:
*Main> f5 ["a","b","c"]
["a","b","c"]
*Main> f5 [1,2,3]
[1,2,3]
答案 0 :(得分:2)
你可以这样做:
f5 xs = [take index xs | (x, index) <- zip xs [1..]]
对于列表中的每个元素,创建一个包含该元素及其索引的元组,从1开始。然后,通过使用take
,对于压缩列表中的每个元素,从原始列表中获取适当数量的元素被采取。要采用的元素数量在索引中指定。
实际上,我们甚至不需要元组中的x
元素,因此可以将其重写为
f5 xs = [take index xs | (_ ,index) <- zip xs [1..]]
答案 1 :(得分:1)
这也有效
foldr (\x rest -> [x]:(map (x:) rest)) [] [1,2,3,4]