我希望将列表中的每个第二个元素加倍。这是代码 -
doubleSec n [] = []
doubleSec n (x:xs)
| n==1 = x*2 : doubleSec 0 xs
| otherwise = x : doubleSec 1 xs
doubleSecond xs =
doubleSec 0 xs
如何在单个函数中压缩此逻辑?
答案 0 :(得分:8)
您可以像这样匹配列表中的模式
doubleSec :: [Int] -> [Int]
doubleSec [] = []
doubleSec [x] = [x]
doubleSec (x : y : xs) = x : 2* y : doubleSec xs
让你对第二个元素做特定的事情
答案 1 :(得分:3)
这个怎么样
doubleSecond xs = map (\(x,i) -> if odd i then x*2 else x) (zip xs [0..])
答案 2 :(得分:2)
此方法将保留O(n)运行时间:
doubleSecond xs =
[ if isOddStep then 2 * x else x |
(isOddStep, x) <- zip (cycle [False, True]) xs ]
@DavidFletcher更简洁的版本:
doubleSecond = zipWith ($) (cycle [id, (2*)])
或:
doubleSecond = zipWith id (cycle [id, (2*)])
由@Carl建议。