4

I can see how it does it on

(foldl * 1 '(1 2 3 4 5)) == 120
(foldr * 1 '(1 2 3 4 5)) == 120

but I can't figure out how it gets 2 for (foldl - 1 '(1 2 3 4 5)) == 2

I would've thought (foldl - 1 '(1 2 3 4 5)) would be ((((1-1)-2)-3)-4)-5), a negative number. What did I miss?

I can tho see why (foldl + 1 '(1 2 3 4 5)) == 16

  • See also [this question](https://stackoverflow.com/questions/8778492/why-is-foldl-defined-in-a-strange-way-in-racket) and its answers for why this is. There are arguments for both ways of defining `foldl`, but this one was chosen for Racket because the accumulator-last version is more consistent with `foldr`, because then both of them take functions that take the accumulator as the last argument. – Alex Knauth Apr 30 '16 at 21:21
  • Also know that Scheme (like the Standard, AKA R6RS for now) has a library with the procedures `fold-right` and `fold-left` where the placement of the accumulator changes. I seldom use those as [SRFI-1](http://srfi.schemers.org/srfi-1/srfi-1.html) has lots of support and use the same accumulator placement for `fold` and `fold-right`, even from [`#!racket`](https://docs.racket-lang.org/srfi/srfi-1.html). – Sylwester May 02 '16 at 21:27

1 Answers1

6

(foldl - 1 '(1 2 3 4 5)) is actually equivalent to (- 5 (- 4 (- 3 (- 2 (- 1 1))))), or, in infix, 5 - (4 - (3 - (2 - (1 - 1)))).

Likewise, (foldr - 1 '(1 2 3 4 5)) is actually equivalent to (- 1 (- 2 (- 3 (- 4 (- 5 1))))), or, in infix, 1 - (2 - (3 - (4 - (5 - 1)))).

C. K. Young
  • 219,335
  • 46
  • 382
  • 435