我有一个清单L
L = [ [0, 3, 1], [7, 2], [5, 11], [7],[] ]
我需要输出返回列表列表,但对于每个偶数子列表,它应该反转它,以便输出为:
L = [ [1, 3, 0], [7, 2], [11, 5], [7],[] ]
假设我们从0开始计算位置。
我可能需要获取有关列表包含多少个子列表的信息,然后反转每个偶数子列表。
答案 0 :(得分:3)
这是Haskell解决方案的骨架,通过直接模式匹配:
reverseEverySecond :: [[a]] -> [[a]]
reverseEverySecond [] = []
reverseEverySecond [x] = [reverse x]
reverseEverySecond (x : y : ys) = ... -- use reverse appropriately and recurse on ys
答案 1 :(得分:1)
要反转单个列表,您只需使用内置的reverse
函数即可。对于在交替元素上进行操作,有几种方法可以解决它。你可以写一个像这样的函数
addEveryOther :: Int -> [Int] -> [Int]
addEveryOther n (x:y:xs) = x + n : y : addEveryOther xs
addEveryOther n (x:[]) = x + n : []
addEveryOther n [] = []
或者,您可以执行类似
的操作addEveryOther n xs = map go $ zip [0..] xs
where
go (i, x) = if even i then x + n else x
但这可能会更慢,因为它涉及更多操作和创建,然后立即破坏元组。
答案 2 :(得分:1)
我建议将
组合起来cycle [id, reverse] :: [[a] -> [a]]
zip :: [a] -> [b] -> [(a, b)]
map (uncurry ($)) :: [(a -> b, a)] -> [b]