I am close to understanding foldr
and foldl
but not quite there yet.
I understand that foldr
is basically the stack implementation of performing some function on a list from "right to left".
So for foldr
:
(define (fn-for-lon lon)
(cond [(empty? lon) 0]
[else
(+ (first lon)
(fn-for-lon (rest lon))]))
Is basically the equivalent of:
(foldr + 0 lon)
And I understand that foldl
is basically the tail recursive, accumulator version that goes from "left to right".
So for foldl
:
(define (fn-for-lon lon0)
(local [(define (fn-for-lon lon acc)
(cond [(empty? lon) acc]
[else
(fn-for-lon (rest lon) (+ acc (first lon)))]
(fn-for-lon lon0)))
Is basically the equivalent of:
(foldl + 0 lon)
But what happens once you introduce two variables? I've tried to read on the topic but I just can't grasp it because no one talks about what is happening behind the scenes.
I'm really confused to whether or not the second argument is "base" or "init" or if it just depends on whether or not one or two variables are taken in the function. In the foldl example I gave it would seem to be the init acc value (which I suppose ends up being the base case), but in the foldr it would be the base case. Is it just because I only use an operator for the proc?
(foldr (lambda (a b) (cons (add1 a) b)) empty (list 1 2 3 4))
Something like the above I really just lose all understanding. I understand what to do, but not really what is happening in the background. This causes me to lose my track in more complex problems.
Is this the exact same thing and b
is just the empty
? Does b
temporarily take on the (rest lon)
?
(define (fn-for-lon lon)
(cond [(empty? lon) empty]
[else
(cons (add1 (first lon))
(fn-for-lon (rest lon)))]))