Saturday, 4 June 2016

Haskell: Double every other element of a list

Double every other element of a list starting from left.

For example,
List = [2, 4, 6, 8, 10] Result like [4, 4, 12, 8, 20]
List = [3, 4, 5, 6] Result like [6, 4, 10, 6]
  

doubleEveryOther.hs
doubleOther [] = []
doubleOther (x:y:xs) = (2*x) : y : doubleOther xs
doubleOther (x:xs) = (2*x) : doubleOther xs

*Main> :load doubleEveryOther.hs
[1 of 1] Compiling Main             ( doubleEveryOther.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> doubleOther [2, 3, 5]
[4,3,10]
*Main> 
*Main> doubleOther [2, 3, 5, 7, 11]
[4,3,10,7,22]
*Main> 
*Main> doubleOther [2]
[4]
*Main> 
*Main> doubleOther []
[]



Previous                                                 Next                                                 Home

No comments:

Post a Comment