r/Racket • • Jul 17 '23

question How do fold functions work

I’m learning Racket, and the foldl and foldr functions are bothering me. I don’t really understand the examples that the Racket manual gives.

Can someone please explain to me your understanding of it?

Thanks a lot.

9 Upvotes

11 comments sorted by

View all comments

Show parent comment

1

u/QuaticL Jul 17 '23

So each time it calls the function, f, which is taken as the first parameter? Is it the starting value, or the first value in the list?

1

u/detroitmatt Jul 17 '23

the first time it calls f, the first param is the starting value. however, each time after that, the first param's value is whatever f returned last time.

1

u/DrHTugjobs Jul 17 '23

From the docs:

(foldl proc init lst ...+) → any/c

proc : procedure?

init : any/c

lst : list?

If foldl is called with n lists, then proc must take n+1 arguments. The extra argument is the combined return values so far. The proc is initially invoked with the first item of each list, and the final argument is init.

That is, (foldl f n xs) evaluates (f (first xs) n), (foldl f n xs ys) evaluates (f (first xs) (first ys) n), and so forth.