orome
orome

Reputation: 48566

How do I accumulate repeated application of a function to a list of values?

How do I accumulate the successive application of a function to a list of values in Haskell?

I'm not sure I'm phrasing that right, but what I'm looking for, for example, is that I have a list values of type X,

l = [a, b, c, d, e]

and a function

f :: X -> X -> X

and I want

(f e (f d (f c (f b a))))

which I think can perhaps be expressed with $ somehow.

I see that Haskell has some fold functions, but I can't quite figure out how to get it to work like the fold operations I'm familiar with.

Upvotes: 1

Views: 424

Answers (3)

amalloy
amalloy

Reputation: 92117

Isn't this just foldl1 (flip f) l? You want a left fold, and you want the operation to start with the first item in the list rather than a specific accumulator.

Upvotes: 6

luqui
luqui

Reputation: 60503

Play with simple-reflect to figure it out.

ghci> import Debug.SimpleReflect
ghci> foldl1 f [a,b,c,d,e]
f (f (f (f a b) c) d) e
ghci> foldl (flip f) z [a,b,c,d,e]
f e (f d (f c (f b (f a z))))

And so on...

Upvotes: 4

ErikR
ErikR

Reputation: 52049

Well, your function f really has type:

f :: X -> X -> X

Then the expression you are interested in is:

foldr1 f [e, d, c, a, b]  -- note the twist at the end.

If you want to compute:

f e (f d (f c (f b a)))  -- note last term is: f b a

then it is just:

foldr1 f [e, d, c, b, a]

Upvotes: 5

Related Questions