Recently I am trying to solve a problem using Foldr. The task is following:
In:[5,1,3,8,2,4,7,1]
Out:[16,8]
It means, I will double those element of the input list which is in the odd index position and even digit. I wrote the program without using foldr which is following:(It shows pattern match failure: head[])
findPos list elt =
map fst $ filter ((elt==).snd) $ zip [0..] list
doublePos [] = []
doublePos (x:xs)
| ((head(findPos xs x)`mod` 2) /= 0) && (x `mod` 2 == 0) =
[2*x] ++ doublePos xs
| otherwise = doublePos xs
How do I write this program using foldr?
foldrisn’t really a good choice for this function, as you need to pass the parity of the index of each element from the front of the list.A list comprehension is probably the cleanest:
or you could use plain old recursion:
Though, if you must use
foldr, you can do it by having the accumulator be a functionwhich takes the parity of the current index as an argument: