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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…