I have a list [a,b,c,d,e] and an initial value u (obviously a,b,c,d,e represent values). I want to apply a function to e and u, let’s say f(e,u). I then want to apply the function f(d, f(e, u)) and then f(c, f(d, f(e, u))) etc. I have looked at “iterate”, but I cannot work out how to apply iterate to each element in a list.
My list:
a = take 101 (0 : concat [[(1%1),(2*k%1),(1%1)] | k <- [1..40]])
How would I go about implementing this in Haskell?
Thanks,
Sam.
The function you describe is called a “fold“, in this case a “right fold” because it is applied from right to left. It is implemented in the Prelude as the
foldrfunction.For instance, if we take the function
(++)that concatenates two strings, and apply it to an initial element and list of strings: