I'm start learning haskell now but I've a case where I couldn't find the solution to solve it
Case:
list = [4, 9, 2, 4, 2]
Wanna become:
list = [4, 18, 2, 8, 2]
It's like multiplying 2 only on odd indexes, can we do this in Haskell?
I'm start learning haskell now but I've a case where I couldn't find the solution to solve it
Case:
list = [4, 9, 2, 4, 2]
Wanna become:
list = [4, 18, 2, 8, 2]
It's like multiplying 2 only on odd indexes, can we do this in Haskell?
You can make an infinite list that interleaves id
and (2*)
with cycle [id, (2*)]
, then we apply these functions to the elements by using zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
:
zipWith ($) (cycle [id, (2*)]) [4, 9, 2, 4, 2]
You can define this function recursively. Just consider what would be the result of calling it on an empty list, a list with one element, a list with two elements or more.
map_odd :: (a -> a) -> [a] -> [a]
map_odd f [] = []
map_odd f [x] = [x]
map_odd f (a:b:l) = a : f b : map_odd f l
Note how function f
needs to have type a -> a
, not a generic a -> b
, because it's only applied to some elements in the list.