2

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?

Irwan
  • 104
  • 8
  • 1
    Yes you can. Have you try writing a recursive function that does that? What would it do to the empty list? What would it do with a list of one element? What would it do with a list of two elements or more? – Stef Jan 01 '22 at 11:14

2 Answers2

7

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]
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
4

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.

Stef
  • 13,242
  • 2
  • 17
  • 28