Haskell - how to iterate list elements in reverse order in an elegant way?

Viewed 4525

I'm trying to write a function that given a list of numbers, returns a list where every 2nd number is doubled in value, starting from the last element. So if the list elements are 1..n, n-th is going to be left as-is, (n-1)-th is going to be doubled in value, (n-2)-th is going to be left as-is, etc.

So here's how I solved it:

MyFunc :: [Integer] -> [Integer]
MyFunc xs = reverse (MyFuncHelper (reverse xs))

MyFuncHelper :: [Integer] -> [Integer]
MyFuncHelper []       = []
MyFuncHelper (x:[])   = [x]
MyFuncHelper (x:y:zs) = [x,y*2] ++ MyFuncHelper zs

And it works:

MyFunc [1,1,1,1] = [2,1,2,1]
MyFunc [1,1,1] = [1,2,1]

However, I can't help but think there has to be a simpler solution than reversing the list, processing it and then reversing it again. Could I simply iterate the list backwards? If yes, how?

5 Answers
Related