最近我正在尝试使用 Foldr 解决一个问题。任务如下:
In:[5,1,3,8,2,4,7,1]
Out:[16,8]
这意味着,我会将输入列表中位于奇数索引位置和偶数位的元素加倍。我在没有使用 foldr 的情况下编写了程序,如下所示:(它显示模式匹配失败:head[])
findPos list elt =
map fst $ filter ((elt==).snd) $ zip [0..] list
doublePos [] = []
doublePos (x:xs)
| ((head(findPos xs x)`mod` 2) /= 0) && (x `mod` 2 == 0) =
[2*x] ++ doublePos xs
| otherwise = doublePos xs
如何使用 foldr 编写此程序?