Haskell: Double every 2nd element in list

You can avoid "empty list" exceptions with some smart pattern matching.

double2nd (x:y:xs) = x : 2 * y : double2nd xs
double2nd a = a

this is simply syntax sugar for the following

double2nd xss = case xss of
    x:y:xs -> x : 2 * y : double2nd xs
    a -> a

the pattern matching is done in order, so xs will be matched against the pattern x:y:xs first. Then if that fails, the catch-all pattern a will succeed.


That's not bad, modulo the fixes suggested. Once you get more familiar with the base library you'll likely avoid explicit recursion in favor of some higher level functions, for example, you could create a list of functions where every other one is *2 and apply (zip) that list of functions to your list of numbers:

double = zipWith ($) (cycle [id,(*2)])

Tags:

Haskell