In Haskell, like in many other functional languages, the function foldl
is defined such that, for example, foldl (-) 0 [1,2,3,4] = -10
.
This is OK, because foldl (-) 0 [1, 2,3,4]
is, by definition, ((((0 - 1) - 2) - 3) - 4)
.
But, in Racket, (foldl - 0 '(1 2 3 4))
is 2, because Racket "intelligently" calculates like this: (4 - (3 - (2 - (1 - 0))))
, which indeed is 2.
Of course, if we define auxiliary function flip, like this:
(define (flip bin-fn)
(lambda (x y)
(bin-fn y x)))
then we could in Racket achieve the same behavior as in Haskell: instead of (foldl - 0 '(1 2 3 4))
we can write: (foldl (flip -) 0 '(1 2 3 4))
The question is: Why is foldl
in racket defined in such an odd (nonstandard and nonintuitive) way, differently than in any other language?
fold-left
is consistent with what you're expecting:(fold-left - 0 '(1 2 3 4))
is-10
and(fold-left cons '() '(1 2 3 4))
is((((() . 1) . 2) . 3) . 4)
. – erjiang