减少这个 Haskell 函数

Reducing this Haskell function

我想将列表的每个第二个元素加倍。这是代码-

doubleSec n [] = []
doubleSec n (x:xs)
    | n==1 = x*2 : doubleSec 0 xs
    | otherwise = x : doubleSec 1 xs 

doubleSecond xs =
    doubleSec 0 xs

如何在单个函数中压缩此逻辑?

您可以像这样匹配列表中的模式

doubleSec :: [Int] -> [Int]
doubleSec [] = []
doubleSec [x] = [x]
doubleSec (x : y : xs) = x : 2* y : doubleSec xs

允许您对第二个元素执行特定操作

此方法将保留 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 所建议。

这个怎么样

doubleSecond xs = map (\(x,i) -> if odd i then x*2 else x) (zip xs [0..])